midnight-wallet-cli 0.1.7 → 0.1.9

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.
Files changed (3) hide show
  1. package/dist/mcp-server.js +217 -2764
  2. package/dist/wallet.js +263 -3573
  3. package/package.json +2 -2
package/dist/wallet.js CHANGED
@@ -1,988 +1,51 @@
1
1
  #!/usr/bin/env node
2
- var __defProp = Object.defineProperty;
3
- var __export = (target, all) => {
4
- for (var name in all)
5
- __defProp(target, name, {
6
- get: all[name],
7
- enumerable: true,
8
- configurable: true,
9
- set: (newValue) => all[name] = () => newValue
10
- });
11
- };
12
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
13
-
14
- // src/lib/argv.ts
15
- function parseArgs(argv) {
16
- const args = argv ?? process.argv.slice(2);
17
- const positionals = [];
18
- const flags = {};
19
- let i = 0;
20
- while (i < args.length) {
21
- const arg = args[i];
22
- if (arg.startsWith("--")) {
23
- const key = arg.slice(2);
24
- const next = args[i + 1];
25
- if (next !== undefined && !next.startsWith("-")) {
26
- flags[key] = next;
27
- i += 2;
28
- } else {
29
- flags[key] = true;
30
- i += 1;
31
- }
32
- } else if (arg.startsWith("-") && arg.length === 2) {
33
- const key = arg.slice(1);
34
- const next = args[i + 1];
35
- if (next !== undefined && !next.startsWith("-")) {
36
- flags[key] = next;
37
- i += 2;
38
- } else {
39
- flags[key] = true;
40
- i += 1;
41
- }
42
- } else {
43
- positionals.push(arg);
44
- i += 1;
45
- }
46
- }
47
- return {
48
- command: positionals[0],
49
- subcommand: positionals[1],
50
- positionals: positionals.slice(2),
51
- flags
52
- };
53
- }
54
- function getFlag(args, name) {
55
- const value = args.flags[name];
56
- if (value === undefined || value === true)
57
- return;
58
- return value;
59
- }
60
- function hasFlag(args, name) {
61
- return name in args.flags;
62
- }
63
- function requireFlag(args, name, description) {
64
- const value = getFlag(args, name);
65
- if (value === undefined) {
66
- throw new Error(`Missing required flag: --${name} <${description}>`);
67
- }
68
- return value;
69
- }
70
-
71
- // src/lib/constants.ts
72
- var GENESIS_SEED = "0000000000000000000000000000000000000000000000000000000000000001", NATIVE_TOKEN_TYPE = "0000000000000000000000000000000000000000000000000000000000000000", TOKEN_DECIMALS = 6, TOKEN_MULTIPLIER = 1e6, DUST_COST_OVERHEAD = 1000000000000n, DUST_FEE_BLOCKS_MARGIN = 5, SYNC_TIMEOUT_MS = 300000, PRE_SEND_SYNC_TIMEOUT_MS = 1e4, DUST_TIMEOUT_MS = 120000, PROOF_TIMEOUT_MS = 300000, BALANCE_CHECK_TIMEOUT_MS = 60000, TX_TTL_MINUTES = 10, MAX_RETRY_ATTEMPTS = 3, DUST_REGISTRATION_TIMEOUT_MS = 600000, DUST_REGISTRATION_RETRY_DELAY_MS = 15000, STALE_UTXO_ERROR_CODE = 115, MIDNIGHT_DIR = ".midnight", DEFAULT_WALLET_FILENAME = "wallet.json", DEFAULT_CONFIG_FILENAME = "config.json", DIR_MODE = 448, FILE_MODE = 384, LOCALNET_DIR_NAME = "localnet";
73
-
74
- // src/ui/colors.ts
75
- function isColorEnabled() {
76
- return !("NO_COLOR" in process.env);
77
- }
78
- function fg(text, code) {
79
- if (!isColorEnabled())
80
- return text;
81
- return `${ESC}38;5;${code}m${text}${RESET}`;
82
- }
83
- function bold(text) {
84
- if (!isColorEnabled())
85
- return text;
86
- return `${ESC}1m${text}${RESET}`;
87
- }
88
- function dim(text) {
89
- if (!isColorEnabled())
90
- return text;
91
- return `${ESC}2m${text}${RESET}`;
92
- }
93
- function teal(text) {
94
- return fg(text, TEAL);
95
- }
96
- function red(text) {
97
- return fg(text, RED_CODE);
98
- }
99
- function green(text) {
100
- return fg(text, GREEN_CODE);
101
- }
102
- function yellow(text) {
103
- return fg(text, YELLOW_CODE);
104
- }
105
- function white(text) {
106
- return fg(text, WHITE_CODE);
107
- }
108
- function gray(text) {
109
- return fg(text, DIM_GRAY);
110
- }
111
- var ESC = "\x1B[", RESET = "\x1B[0m", TEAL = 38, WHITE_CODE = 15, DIM_GRAY = 245, RED_CODE = 196, GREEN_CODE = 40, YELLOW_CODE = 226;
112
-
113
- // src/ui/format.ts
114
- function header(title, width = DEFAULT_WIDTH) {
115
- const paddedTitle = ` ${title} `;
116
- const remaining = width - paddedTitle.length;
117
- if (remaining <= 0)
118
- return bold(paddedTitle);
119
- const left = Math.floor(remaining / 2);
120
- const right = remaining - left;
121
- return bold("═".repeat(left) + paddedTitle + "═".repeat(right));
122
- }
123
- function divider(width = DEFAULT_WIDTH) {
124
- return dim("─".repeat(width));
125
- }
126
- function keyValue(key, value, padWidth = 16) {
127
- const paddedKey = (key + ":").padEnd(padWidth);
128
- return ` ${gray(paddedKey)}${value}`;
129
- }
130
- function toNight(microNight) {
131
- const isNegative = microNight < 0n;
132
- const abs = isNegative ? -microNight : microNight;
133
- const multiplier = BigInt(10 ** TOKEN_DECIMALS);
134
- const whole = abs / multiplier;
135
- const frac = abs % multiplier;
136
- const fracStr = frac.toString().padStart(TOKEN_DECIMALS, "0");
137
- const sign = isNegative ? "-" : "";
138
- return `${sign}${whole}.${fracStr}`;
139
- }
140
- function formatNight(microNight) {
141
- return `${toNight(microNight)} NIGHT`;
142
- }
143
- function toDust(specks) {
144
- const isNegative = specks < 0n;
145
- const abs = isNegative ? -specks : specks;
146
- const multiplier = 10n ** BigInt(DUST_DECIMALS);
147
- const whole = abs / multiplier;
148
- const frac = abs % multiplier;
149
- const fracStr = frac.toString().padStart(DUST_DECIMALS, "0");
150
- const trimmed = fracStr.replace(/0+$/, "").padEnd(6, "0");
151
- const sign = isNegative ? "-" : "";
152
- return `${sign}${whole}.${trimmed}`;
153
- }
154
- function formatDust(specks) {
155
- return `${toDust(specks)} DUST`;
156
- }
157
- function formatAddress(address, truncate = false) {
158
- const display = truncate && address.length > 20 ? address.slice(0, 10) + "…" + address.slice(-8) : address;
159
- return teal(display);
160
- }
161
- function wrapLine(line, maxWidth) {
162
- const visible = stripAnsi(line);
163
- if (visible.length <= maxWidth)
164
- return [line];
165
- const words = line.split(/(\s+)/);
166
- const result = [];
167
- let currentLine = "";
168
- let currentLen = 0;
169
- for (const word of words) {
170
- const wordLen = stripAnsi(word).length;
171
- if (currentLen + wordLen > maxWidth && currentLen > 0) {
172
- result.push(currentLine);
173
- currentLine = word.trimStart();
174
- currentLen = stripAnsi(currentLine).length;
175
- } else {
176
- currentLine += word;
177
- currentLen += wordLen;
178
- }
179
- }
180
- if (currentLine.length > 0)
181
- result.push(currentLine);
182
- return result;
183
- }
184
- function box(lines, style = "light", maxWidth = 70) {
185
- const chars = style === "heavy" ? { tl: "╔", tr: "╗", bl: "╚", br: "╝", h: "═", v: "║" } : { tl: "┌", tr: "┐", bl: "└", br: "┘", h: "─", v: "│" };
186
- const contentMaxWidth = maxWidth - 4;
187
- const expanded = [];
188
- for (const line of lines) {
189
- const subLines = line.split(`
190
- `);
191
- for (const sub of subLines) {
192
- expanded.push(...wrapLine(sub, contentMaxWidth));
193
- }
194
- }
195
- const maxLen = Math.max(...expanded.map((l) => stripAnsi(l).length));
196
- const innerWidth = Math.max(maxLen + 2, 20);
197
- const top = chars.tl + chars.h.repeat(innerWidth) + chars.tr;
198
- const bottom = chars.bl + chars.h.repeat(innerWidth) + chars.br;
199
- const body = expanded.map((line) => {
200
- const visibleLen = stripAnsi(line).length;
201
- const padding = innerWidth - visibleLen - 2;
202
- return `${chars.v} ${line}${" ".repeat(Math.max(0, padding))} ${chars.v}`;
203
- });
204
- return [top, ...body, bottom].join(`
205
- `);
206
- }
207
- function errorBox(error, suggestion) {
208
- const errorLines = error.split(`
209
- `);
210
- const lines = errorLines.map((line, i) => i === 0 ? red(bold("Error: ")) + red(line) : red(line));
211
- if (suggestion) {
212
- lines.push("");
213
- lines.push(dim("Suggestion: ") + suggestion);
214
- }
215
- const output = box(lines, "heavy");
216
- if (isColorEnabled()) {
217
- return output.replace(/[╔╗╚╝═║]/g, (match) => red(match));
218
- }
219
- return output;
220
- }
221
- function successMessage(msg, txHash) {
222
- const check = green("✓");
223
- const parts = [`${check} ${msg}`];
224
- if (txHash) {
225
- parts.push(keyValue("Transaction", teal(txHash)));
226
- }
227
- return parts.join(`
228
- `);
229
- }
230
- var DEFAULT_WIDTH = 60, DUST_DECIMALS = 15, stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
231
- var init_format = () => {
232
- };
233
-
234
- // src/lib/exit-codes.ts
235
- function classifyError(err) {
236
- const msg = (err.message ?? "").toLowerCase();
237
- if (msg.includes("operation cancelled") || msg.includes("operation aborted") || msg === "cancelled" || msg === "aborted") {
238
- return { exitCode: EXIT_CANCELLED, errorCode: ERROR_CODES.CANCELLED };
239
- }
240
- if (msg.includes("wallet file not found") || msg.includes("wallet") && msg.includes("not found")) {
241
- return { exitCode: EXIT_WALLET_NOT_FOUND, errorCode: ERROR_CODES.WALLET_NOT_FOUND };
242
- }
243
- if (msg.includes("missing required flag") || msg.includes("missing amount") || msg.includes("missing recipient") || msg.includes("missing config key") || msg.includes("missing or invalid subcommand") || msg.includes("unknown command") || msg.includes("cannot specify both") || msg.includes("invalid bip-39") || msg.includes("seed must be") || msg.includes("key index must be") || msg.includes("usage:")) {
244
- return { exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.INVALID_ARGS };
245
- }
246
- if (msg.includes("proof") && msg.includes("timeout")) {
247
- return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.PROOF_TIMEOUT };
248
- }
249
- if (msg.includes("stale utxo") || msg.includes("error code 115") || msg.includes("errorcode: 115")) {
250
- return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.STALE_UTXO };
251
- }
252
- if (msg.includes("no dust") || msg.includes("dust") && (msg.includes("required") || msg.includes("available") || msg.includes("insufficient"))) {
253
- return { exitCode: EXIT_INSUFFICIENT_BALANCE, errorCode: ERROR_CODES.DUST_REQUIRED };
254
- }
255
- if (msg.includes("insufficient") || msg.includes("not enough")) {
256
- return { exitCode: EXIT_INSUFFICIENT_BALANCE, errorCode: ERROR_CODES.INSUFFICIENT_BALANCE };
257
- }
258
- if (msg.includes("rejected") || msg.includes("transaction failed")) {
259
- return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.TX_REJECTED };
260
- }
261
- if (msg.includes("econnrefused") || msg.includes("enotfound") || msg.includes("etimedout") || msg.includes("websocket") || msg.includes("connection refused") || msg.includes("network") && msg.includes("error")) {
262
- return { exitCode: EXIT_NETWORK_ERROR, errorCode: ERROR_CODES.NETWORK_ERROR };
263
- }
264
- return { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.UNKNOWN };
265
- }
266
- var EXIT_GENERAL_ERROR = 1, EXIT_INVALID_ARGS = 2, EXIT_WALLET_NOT_FOUND = 3, EXIT_NETWORK_ERROR = 4, EXIT_INSUFFICIENT_BALANCE = 5, EXIT_TX_REJECTED = 6, EXIT_CANCELLED = 7, ERROR_CODES;
267
- var init_exit_codes = __esm(() => {
268
- ERROR_CODES = {
269
- INVALID_ARGS: "INVALID_ARGS",
270
- WALLET_NOT_FOUND: "WALLET_NOT_FOUND",
271
- NETWORK_ERROR: "NETWORK_ERROR",
272
- INSUFFICIENT_BALANCE: "INSUFFICIENT_BALANCE",
273
- TX_REJECTED: "TX_REJECTED",
274
- STALE_UTXO: "STALE_UTXO",
275
- PROOF_TIMEOUT: "PROOF_TIMEOUT",
276
- DUST_REQUIRED: "DUST_REQUIRED",
277
- CANCELLED: "CANCELLED",
278
- UNKNOWN: "UNKNOWN"
279
- };
280
- });
281
-
282
- // src/lib/json-output.ts
283
- function suppressStderr() {
284
- const original = process.stderr.write;
285
- process.stderr.write = () => true;
286
- return () => {
287
- process.stderr.write = original;
288
- };
289
- }
290
- function setCaptureTarget(fn) {
291
- captureTarget = fn;
292
- }
293
- function writeJsonResult(data) {
294
- const json = JSON.stringify(data) + `
295
- `;
296
- if (captureTarget) {
297
- captureTarget(json);
298
- } else {
299
- process.stdout.write(json);
300
- }
301
- }
302
- function writeJsonError(err, errorCode, exitCode) {
303
- process.stdout.write(JSON.stringify({
304
- error: true,
305
- code: errorCode,
306
- message: err.message,
307
- exitCode
308
- }) + `
309
- `);
310
- }
311
- var captureTarget = null;
312
-
313
- // package.json
314
- var package_default;
315
- var init_package = __esm(() => {
316
- package_default = {
317
- name: "midnight-wallet-cli",
318
- version: "0.1.7",
319
- type: "module",
320
- description: "Git-style CLI wallet for the Midnight blockchain",
321
- license: "Apache-2.0",
322
- bin: {
323
- midnight: "dist/wallet.js",
324
- mn: "dist/wallet.js",
325
- "midnight-wallet-cli": "dist/wallet.js",
326
- "midnight-wallet-mcp": "dist/mcp-server.js"
327
- },
328
- files: [
329
- "dist"
330
- ],
331
- scripts: {
332
- wallet: "tsx src/wallet.ts",
333
- build: 'bun build src/wallet.ts --outfile dist/wallet.js --target node --format esm --packages external --banner "#!/usr/bin/env node" && bun build src/mcp-server.ts --outfile dist/mcp-server.js --target node --format esm --packages external --banner "#!/usr/bin/env node"',
334
- mcp: "tsx src/mcp-server.ts",
335
- prepublishOnly: "npm run build && npm run test",
336
- test: "vitest run",
337
- "test:watch": "vitest",
338
- typecheck: "tsc --noEmit"
339
- },
340
- dependencies: {
341
- "@midnight-ntwrk/ledger-v7": "7.0.0",
342
- "@midnight-ntwrk/midnight-js-network-id": "3.0.0",
343
- "@midnight-ntwrk/midnight-js-types": "3.0.0",
344
- "@midnight-ntwrk/wallet-sdk-abstractions": "1.0.0",
345
- "@midnight-ntwrk/wallet-sdk-address-format": "3.0.0",
346
- "@midnight-ntwrk/wallet-sdk-dust-wallet": "1.0.0",
347
- "@midnight-ntwrk/wallet-sdk-facade": "1.0.0",
348
- "@midnight-ntwrk/wallet-sdk-hd": "3.0.0",
349
- "@midnight-ntwrk/wallet-sdk-shielded": "1.0.0",
350
- "@midnight-ntwrk/wallet-sdk-unshielded-wallet": "1.0.0",
351
- "@modelcontextprotocol/sdk": "^1.27.1",
352
- "@scure/bip39": "^2.0.1",
353
- rxjs: "^7.8.1",
354
- ws: "^8.19.0"
355
- },
356
- devDependencies: {
357
- "@types/node": "^22.19.13",
358
- "@types/ws": "^8.18.1",
359
- tsx: "^4.21.0",
360
- typescript: "^5.9.3",
361
- vitest: "^3.2.4"
362
- }
363
- };
364
- });
365
-
366
- // src/lib/pkg.ts
367
- var PKG_NAME, PKG_VERSION, PKG_DESCRIPTION;
368
- var init_pkg = __esm(() => {
369
- init_package();
370
- PKG_NAME = package_default.name;
371
- PKG_VERSION = package_default.version;
372
- PKG_DESCRIPTION = package_default.description;
373
- });
374
-
375
- // src/lib/run-command.ts
376
- async function captureCommand(handler, args, signal) {
377
- const chunks = [];
378
- setCaptureTarget((json) => chunks.push(json));
379
- const originalStderr = process.stderr.write;
380
- process.stderr.write = () => true;
381
- try {
382
- args.flags.json = true;
383
- await handler(args, signal);
384
- const raw = chunks.join("").trim();
385
- if (!raw)
386
- return {};
387
- return JSON.parse(raw);
388
- } finally {
389
- setCaptureTarget(null);
390
- process.stderr.write = originalStderr;
391
- }
392
- }
393
- var init_run_command = () => {
394
- };
395
-
396
- // src/lib/derive-address.ts
397
- import { HDWallet, Roles } from "@midnight-ntwrk/wallet-sdk-hd";
398
- import { createKeystore, PublicKey } from "@midnight-ntwrk/wallet-sdk-unshielded-wallet";
399
- import { NetworkId } from "@midnight-ntwrk/wallet-sdk-abstractions";
400
- function deriveUnshieldedAddress(seedBuffer, networkName, keyIndex = 0) {
401
- const networkId = NETWORK_ID_MAP[networkName];
402
- const hdResult = HDWallet.fromSeed(seedBuffer);
403
- if (hdResult.type !== "seedOk") {
404
- throw new Error("Invalid seed for HD wallet");
405
- }
406
- const derivation = hdResult.hdWallet.selectAccount(0).selectRole(Roles.NightExternal).deriveKeyAt(keyIndex);
407
- if (derivation.type === "keyOutOfBounds") {
408
- throw new Error(`Key index ${keyIndex} out of bounds`);
409
- }
410
- const keystore = createKeystore(derivation.key, networkId);
411
- const publicKey = PublicKey.fromKeyStore(keystore);
412
- return publicKey.address;
413
- }
414
- var NETWORK_ID_MAP;
415
- var init_derive_address = __esm(() => {
416
- NETWORK_ID_MAP = {
417
- preprod: NetworkId.NetworkId.PreProd,
418
- preview: NetworkId.NetworkId.Preview,
419
- undeployed: NetworkId.NetworkId.Undeployed
420
- };
421
- });
422
-
423
- // src/lib/network.ts
424
- import { execSync } from "child_process";
425
- function isValidNetworkName(name) {
426
- return VALID_NETWORK_NAMES.includes(name);
427
- }
428
- function getNetworkConfig(name) {
429
- return { ...NETWORK_CONFIGS[name] };
430
- }
431
- function getValidNetworkNames() {
432
- return VALID_NETWORK_NAMES;
433
- }
434
- function detectNetworkFromAddress(address) {
435
- if (address.startsWith("mn_addr_preprod1"))
436
- return "preprod";
437
- if (address.startsWith("mn_addr_preview1"))
438
- return "preview";
439
- if (address.startsWith("mn_addr_undeployed1"))
440
- return "undeployed";
441
- return null;
442
- }
443
- function detectTestcontainerPorts() {
444
- try {
445
- const output = execSync('docker ps --format "{{.Image}}|{{.Ports}}"', { encoding: "utf-8", timeout: 5000 });
446
- const result = {};
447
- for (const line of output.trim().split(`
448
- `)) {
449
- if (!line)
450
- continue;
451
- const [image, ports] = line.split("|");
452
- const extractHostPort = (containerPort) => {
453
- const regex = new RegExp(`0\\.0\\.0\\.0:(\\d+)->${containerPort}/tcp`);
454
- const match = ports?.match(regex);
455
- return match ? parseInt(match[1], 10) : undefined;
456
- };
457
- if (image.includes("indexer-standalone") || image.includes("indexer")) {
458
- const port = extractHostPort(8088);
459
- if (port)
460
- result.indexerPort = port;
461
- }
462
- if (image.includes("midnight-node")) {
463
- const port = extractHostPort(9944);
464
- if (port)
465
- result.nodePort = port;
466
- }
467
- if (image.includes("proof-server")) {
468
- const port = extractHostPort(6300);
469
- if (port)
470
- result.proofServerPort = port;
471
- }
472
- }
473
- return result;
474
- } catch {
475
- return {};
476
- }
477
- }
478
- function resolveNetworkConfig(name) {
479
- const config = getNetworkConfig(name);
480
- if (name === "undeployed") {
481
- const detected = detectTestcontainerPorts();
482
- if (detected.indexerPort) {
483
- config.indexer = `http://localhost:${detected.indexerPort}/api/v3/graphql`;
484
- config.indexerWS = `ws://localhost:${detected.indexerPort}/api/v3/graphql/ws`;
485
- }
486
- if (detected.nodePort) {
487
- config.node = `ws://localhost:${detected.nodePort}`;
488
- }
489
- if (detected.proofServerPort) {
490
- config.proofServer = `http://localhost:${detected.proofServerPort}`;
491
- }
492
- }
493
- return config;
494
- }
495
- var NETWORK_CONFIGS, VALID_NETWORK_NAMES;
496
- var init_network = __esm(() => {
497
- NETWORK_CONFIGS = {
498
- preprod: {
499
- indexer: "https://indexer.preprod.midnight.network/api/v3/graphql",
500
- indexerWS: "wss://indexer.preprod.midnight.network/api/v3/graphql/ws",
501
- node: "wss://rpc.preprod.midnight.network",
502
- proofServer: "http://localhost:6300",
503
- networkId: "PreProd"
504
- },
505
- preview: {
506
- indexer: "https://indexer.preview.midnight.network/api/v3/graphql",
507
- indexerWS: "wss://indexer.preview.midnight.network/api/v3/graphql/ws",
508
- node: "wss://rpc.preview.midnight.network",
509
- proofServer: "http://localhost:6300",
510
- networkId: "Preview"
511
- },
512
- undeployed: {
513
- indexer: "http://localhost:8088/api/v3/graphql",
514
- indexerWS: "ws://localhost:8088/api/v3/graphql/ws",
515
- node: "ws://localhost:9944",
516
- proofServer: "http://localhost:6300",
517
- networkId: "Undeployed"
518
- }
519
- };
520
- VALID_NETWORK_NAMES = ["preprod", "preview", "undeployed"];
521
- });
522
-
523
- // src/lib/cli-config.ts
524
- import * as fs from "fs";
525
- import * as path from "path";
526
- import { homedir } from "os";
527
- function getConfigDir(configDir) {
528
- return configDir ?? path.join(homedir(), MIDNIGHT_DIR);
529
- }
530
- function getConfigPath(configDir) {
531
- return path.join(getConfigDir(configDir), DEFAULT_CONFIG_FILENAME);
532
- }
533
- function ensureConfigDir(configDir) {
534
- const dir = getConfigDir(configDir);
535
- if (!fs.existsSync(dir)) {
536
- fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE });
537
- }
538
- }
539
- function loadCliConfig(configDir) {
540
- const configPath = getConfigPath(configDir);
541
- if (!fs.existsSync(configPath)) {
542
- return { ...DEFAULT_CLI_CONFIG };
543
- }
544
- let content;
545
- try {
546
- content = fs.readFileSync(configPath, "utf-8");
547
- } catch {
548
- return { ...DEFAULT_CLI_CONFIG };
549
- }
550
- let parsed;
551
- try {
552
- parsed = JSON.parse(content);
553
- } catch {
554
- return { ...DEFAULT_CLI_CONFIG };
555
- }
556
- return {
557
- network: parsed.network && isValidNetworkName(parsed.network) ? parsed.network : DEFAULT_CLI_CONFIG.network
558
- };
559
- }
560
- function saveCliConfig(config, configDir) {
561
- ensureConfigDir(configDir);
562
- const configPath = getConfigPath(configDir);
563
- fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + `
564
- `, { mode: FILE_MODE });
565
- }
566
- function getConfigValue(key, configDir) {
567
- const config = loadCliConfig(configDir);
568
- if (key === "network")
569
- return config.network;
570
- throw new Error(`Unknown config key: "${key}"
571
- Valid keys: ${VALID_CONFIG_KEYS.join(", ")}`);
572
- }
573
- function setConfigValue(key, value, configDir) {
574
- const config = loadCliConfig(configDir);
575
- if (key === "network") {
576
- if (!isValidNetworkName(value)) {
577
- throw new Error(`Invalid network: "${value}"
578
- Valid networks: preprod, preview, undeployed`);
579
- }
580
- config.network = value;
581
- } else {
582
- throw new Error(`Unknown config key: "${key}"
583
- Valid keys: ${VALID_CONFIG_KEYS.join(", ")}`);
584
- }
585
- saveCliConfig(config, configDir);
586
- }
587
- function getValidConfigKeys() {
588
- return VALID_CONFIG_KEYS;
589
- }
590
- var DEFAULT_CLI_CONFIG, VALID_CONFIG_KEYS;
591
- var init_cli_config = __esm(() => {
592
- init_network();
593
- DEFAULT_CLI_CONFIG = {
594
- network: "undeployed"
595
- };
596
- VALID_CONFIG_KEYS = ["network"];
597
- });
598
-
599
- // src/lib/resolve-network.ts
600
- function resolveNetworkName(ctx) {
601
- const flagValue = getFlag(ctx.args, "network");
602
- if (flagValue !== undefined) {
603
- if (!isValidNetworkName(flagValue)) {
604
- throw new Error(`Invalid network: "${flagValue}"
605
- ` + `Valid networks: ${getValidNetworkNames().join(", ")}`);
606
- }
607
- return flagValue;
608
- }
609
- if (ctx.walletNetwork && isValidNetworkName(ctx.walletNetwork)) {
610
- return ctx.walletNetwork;
611
- }
612
- if (ctx.address) {
613
- const detected = detectNetworkFromAddress(ctx.address);
614
- if (detected)
615
- return detected;
616
- }
617
- const cliConfig = loadCliConfig(ctx.configDir);
618
- if (cliConfig.network && isValidNetworkName(cliConfig.network)) {
619
- return cliConfig.network;
620
- }
621
- return "undeployed";
622
- }
623
- function resolveNetwork(ctx) {
624
- const name = resolveNetworkName(ctx);
625
- const config = resolveNetworkConfig(name);
626
- return { name, config };
627
- }
628
- var init_resolve_network = __esm(() => {
629
- init_network();
630
- init_cli_config();
631
- });
632
-
633
- // src/lib/wallet-config.ts
634
- import * as fs2 from "fs";
635
- import * as path2 from "path";
636
- import { homedir as homedir2 } from "os";
637
- function getMidnightDir() {
638
- return path2.join(homedir2(), MIDNIGHT_DIR);
639
- }
640
- function getDefaultWalletPath() {
641
- return path2.join(getMidnightDir(), DEFAULT_WALLET_FILENAME);
642
- }
643
- function ensureMidnightDir() {
644
- const dir = getMidnightDir();
645
- if (!fs2.existsSync(dir)) {
646
- fs2.mkdirSync(dir, { recursive: true, mode: DIR_MODE });
647
- }
648
- }
649
- function loadWalletConfig(walletPath) {
650
- const resolvedPath = walletPath ? path2.resolve(walletPath) : getDefaultWalletPath();
651
- if (!fs2.existsSync(resolvedPath)) {
652
- throw new Error(`Wallet file not found: ${resolvedPath}
653
- ` + `Generate a wallet first: midnight generate --network <name>`);
654
- }
655
- let content;
656
- try {
657
- content = fs2.readFileSync(resolvedPath, "utf-8");
658
- } catch (err) {
659
- throw new Error(`Failed to read wallet file: ${resolvedPath}
660
- ${err.message}`);
661
- }
662
- let config;
663
- try {
664
- config = JSON.parse(content);
665
- } catch {
666
- throw new Error(`Invalid JSON in wallet file: ${resolvedPath}`);
667
- }
668
- if (!config.seed || !config.network || !config.address || !config.createdAt) {
669
- const missing = ["seed", "network", "address", "createdAt"].filter((f) => !config[f]);
670
- throw new Error(`Wallet file is missing required fields (${missing.join(", ")}): ${resolvedPath}`);
671
- }
672
- if (!/^[0-9a-fA-F]+$/.test(config.seed)) {
673
- throw new Error(`Invalid seed format in wallet file (expected hex string): ${resolvedPath}`);
674
- }
675
- if (!isValidNetworkName(config.network)) {
676
- throw new Error(`Invalid network "${config.network}" in wallet file: ${resolvedPath}
677
- ` + `Valid networks: preprod, preview, undeployed`);
678
- }
679
- return config;
680
- }
681
- function saveWalletConfig(config, walletPath) {
682
- const resolvedPath = walletPath ? path2.resolve(walletPath) : getDefaultWalletPath();
683
- if (!walletPath) {
684
- ensureMidnightDir();
685
- } else {
686
- const dir = path2.dirname(resolvedPath);
687
- if (!fs2.existsSync(dir)) {
688
- fs2.mkdirSync(dir, { recursive: true, mode: DIR_MODE });
689
- }
690
- }
691
- fs2.writeFileSync(resolvedPath, JSON.stringify(config, null, 2) + `
692
- `, { mode: FILE_MODE });
693
- return resolvedPath;
694
- }
695
- var init_wallet_config = __esm(() => {
696
- init_network();
697
- });
698
-
699
- // src/commands/generate.ts
700
- var exports_generate = {};
701
- __export(exports_generate, {
702
- default: () => generateCommand
703
- });
704
- import * as fs3 from "fs";
705
- import * as path3 from "path";
706
- import { homedir as homedir3 } from "os";
707
- import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from "@scure/bip39";
708
- import { wordlist } from "@scure/bip39/wordlists/english.js";
709
- async function generateCommand(args) {
710
- const networkName = resolveNetworkName({ args });
711
- const outputPath = getFlag(args, "output");
712
- const seedHex = getFlag(args, "seed");
713
- const mnemonicStr = getFlag(args, "mnemonic");
714
- if (seedHex !== undefined && mnemonicStr !== undefined) {
715
- throw new Error("Cannot specify both --seed and --mnemonic. Use one or the other.");
716
- }
717
- const targetPath = outputPath ? path3.resolve(outputPath) : path3.join(homedir3(), MIDNIGHT_DIR, DEFAULT_WALLET_FILENAME);
718
- if (fs3.existsSync(targetPath) && !hasFlag(args, "force")) {
719
- throw new Error(`Wallet file already exists: ${targetPath}
720
- ` + `Use --force to overwrite, or --output <file> to save to a different path.`);
721
- }
722
- let seedBuffer;
723
- let mnemonic;
724
- if (seedHex !== undefined) {
725
- const cleaned = seedHex.replace(/^0x/, "");
726
- if (cleaned.length !== 64 || !/^[0-9a-fA-F]+$/.test(cleaned)) {
727
- throw new Error("Seed must be a 64-character hex string (32 bytes)");
728
- }
729
- seedBuffer = Buffer.from(cleaned, "hex");
730
- } else if (mnemonicStr !== undefined) {
731
- if (!validateMnemonic(mnemonicStr, wordlist)) {
732
- throw new Error("Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.");
733
- }
734
- mnemonic = mnemonicStr;
735
- seedBuffer = Buffer.from(mnemonicToSeedSync(mnemonic).slice(0, 32));
736
- } else {
737
- mnemonic = generateMnemonic(wordlist, 256);
738
- seedBuffer = Buffer.from(mnemonicToSeedSync(mnemonic).slice(0, 32));
739
- }
740
- const address = deriveUnshieldedAddress(seedBuffer, networkName);
741
- const config = {
742
- seed: seedBuffer.toString("hex"),
743
- network: networkName,
744
- address,
745
- createdAt: new Date().toISOString()
746
- };
747
- if (mnemonic) {
748
- config.mnemonic = mnemonic;
749
- }
750
- const savedPath = saveWalletConfig(config, outputPath);
751
- if (hasFlag(args, "json")) {
752
- const result = {
753
- address,
754
- network: networkName,
755
- seed: seedBuffer.toString("hex"),
756
- file: savedPath,
757
- createdAt: config.createdAt
758
- };
759
- if (mnemonic)
760
- result.mnemonic = mnemonic;
761
- writeJsonResult(result);
762
- return;
763
- }
764
- process.stdout.write(address + `
765
- `);
766
- process.stderr.write(`
767
- ` + header("Wallet Generated") + `
768
-
769
- `);
770
- process.stderr.write(keyValue("Network", networkName) + `
771
- `);
772
- process.stderr.write(keyValue("Address", formatAddress(address)) + `
773
- `);
774
- process.stderr.write(keyValue("File", savedPath) + `
775
- `);
776
- process.stderr.write(`
777
- `);
778
- if (mnemonic) {
779
- process.stderr.write(yellow(bold(" MNEMONIC (save securely!):")) + `
780
- `);
781
- process.stderr.write(` ${mnemonic}
782
-
783
- `);
784
- }
785
- process.stderr.write(yellow(bold(" SEED (hex):")) + `
786
- `);
787
- process.stderr.write(` ${seedBuffer.toString("hex")}
788
-
789
- `);
790
- process.stderr.write(divider() + `
791
- `);
792
- process.stderr.write(dim(" Next: midnight info | midnight balance") + `
793
-
794
- `);
795
- process.stderr.write(green("✓") + ` Wallet saved
796
- `);
797
- }
798
- var init_generate = __esm(() => {
799
- init_derive_address();
800
- init_resolve_network();
801
- init_wallet_config();
802
- init_format();
803
- });
804
-
805
- // src/commands/info.ts
806
- var exports_info = {};
807
- __export(exports_info, {
808
- default: () => infoCommand
809
- });
810
- import * as path4 from "path";
811
- import { homedir as homedir4 } from "os";
812
- async function infoCommand(args) {
813
- const walletPath = getFlag(args, "wallet");
814
- const config = loadWalletConfig(walletPath);
815
- const resolvedPath = walletPath ? path4.resolve(walletPath) : path4.join(homedir4(), MIDNIGHT_DIR, DEFAULT_WALLET_FILENAME);
816
- if (hasFlag(args, "json")) {
817
- writeJsonResult({
818
- address: config.address,
819
- network: config.network,
820
- createdAt: config.createdAt,
821
- file: resolvedPath
822
- });
823
- return;
824
- }
825
- process.stdout.write(config.address + `
826
- `);
827
- process.stderr.write(`
828
- ` + header("Wallet Info") + `
829
-
830
- `);
831
- process.stderr.write(keyValue("Address", formatAddress(config.address)) + `
832
- `);
833
- process.stderr.write(keyValue("Network", config.network) + `
834
- `);
835
- process.stderr.write(keyValue("Created", config.createdAt) + `
836
- `);
837
- process.stderr.write(keyValue("File", resolvedPath) + `
838
- `);
839
- process.stderr.write(`
840
- ` + divider() + `
841
-
842
- `);
843
- }
844
- var init_info = __esm(() => {
845
- init_wallet_config();
846
- init_format();
847
- init_format();
848
- });
849
-
850
- // src/lib/balance-subscription.ts
851
- import WebSocket from "ws";
852
- function checkBalance(address, indexerWS, onProgress) {
853
- return new Promise((resolve4, reject) => {
854
- const ws = new WebSocket(indexerWS, ["graphql-transport-ws"]);
855
- const utxos = new Map;
856
- let txCount = 0;
857
- let highestTxId = 0;
858
- let lastSeenTxId = 0;
859
- let progressReceived = false;
860
- let settled = false;
861
- let timeoutId;
862
- const buildResult = () => {
863
- const balances = new Map;
864
- let utxoCount = 0;
865
- for (const utxo of utxos.values()) {
866
- if (!utxo.spent) {
867
- utxoCount++;
868
- const current = balances.get(utxo.tokenType) ?? 0n;
869
- balances.set(utxo.tokenType, current + utxo.value);
870
- }
871
- }
872
- return { balances, utxoCount, txCount, highestTxId };
873
- };
874
- const settle = () => {
875
- clearTimeout(timeoutId);
876
- };
877
- const checkComplete = () => {
878
- if (!settled && progressReceived && (highestTxId === 0 || lastSeenTxId >= highestTxId)) {
879
- settled = true;
880
- settle();
881
- ws.send(JSON.stringify({ id: "1", type: "complete" }));
882
- ws.close();
883
- resolve4(buildResult());
884
- }
885
- };
886
- ws.on("open", () => {
887
- ws.send(JSON.stringify({ type: "connection_init" }));
888
- });
889
- ws.on("message", (data) => {
890
- const message = JSON.parse(data.toString());
891
- switch (message.type) {
892
- case "connection_ack":
893
- ws.send(JSON.stringify({
894
- id: "1",
895
- type: "subscribe",
896
- payload: {
897
- query: SUBSCRIPTION_QUERY,
898
- variables: { address }
899
- }
900
- }));
901
- break;
902
- case "next": {
903
- if (message.payload?.errors) {
904
- const errMsg = message.payload.errors[0]?.message || "Unknown GraphQL error";
905
- if (!settled) {
906
- settled = true;
907
- settle();
908
- ws.close();
909
- reject(new Error(`GraphQL error: ${errMsg}`));
910
- }
911
- return;
912
- }
913
- const event = message.payload?.data?.unshieldedTransactions;
914
- if (!event)
915
- return;
916
- if (event.__typename === "UnshieldedTransaction") {
917
- txCount++;
918
- const tx = event;
919
- lastSeenTxId = Math.max(lastSeenTxId, tx.transaction.id);
920
- for (const utxo of tx.createdUtxos) {
921
- const key = `${utxo.intentHash}:${utxo.outputIndex}`;
922
- utxos.set(key, {
923
- value: BigInt(utxo.value),
924
- tokenType: utxo.tokenType,
925
- spent: false
926
- });
927
- }
928
- for (const utxo of tx.spentUtxos) {
929
- const key = `${utxo.intentHash}:${utxo.outputIndex}`;
930
- const existing = utxos.get(key);
931
- if (existing) {
932
- existing.spent = true;
933
- }
934
- }
935
- if (onProgress) {
936
- onProgress(lastSeenTxId, highestTxId);
937
- }
938
- checkComplete();
939
- } else if (event.__typename === "UnshieldedTransactionsProgress") {
940
- const progress = event;
941
- highestTxId = progress.highestTransactionId;
942
- progressReceived = true;
943
- checkComplete();
944
- }
945
- break;
946
- }
947
- case "error":
948
- if (!settled) {
949
- settled = true;
950
- settle();
951
- ws.close();
952
- reject(new Error(`GraphQL subscription error: ${JSON.stringify(message.payload)}`));
953
- }
954
- break;
955
- case "complete":
956
- break;
957
- }
958
- });
959
- ws.on("error", (error) => {
960
- if (!settled) {
961
- settled = true;
962
- settle();
963
- reject(new Error(`WebSocket connection failed: ${error.message}`));
964
- }
965
- });
966
- ws.on("close", () => {
967
- if (!settled) {
968
- settled = true;
969
- settle();
970
- reject(new Error(`Indexer closed the connection before balance sync completed. ` + `Indexer: ${indexerWS}`));
971
- }
972
- });
973
- timeoutId = setTimeout(() => {
974
- if (!settled) {
975
- settled = true;
976
- ws.close();
977
- reject(new Error(`Balance check timed out after ${BALANCE_CHECK_TIMEOUT_MS / 1000}s. ` + `Indexer: ${indexerWS}`));
978
- }
979
- }, BALANCE_CHECK_TIMEOUT_MS);
980
- });
981
- }
982
- function isNativeToken(tokenType) {
983
- return tokenType === NATIVE_TOKEN_TYPE;
984
- }
985
- var SUBSCRIPTION_QUERY = `
2
+ var L2=Object.defineProperty;var S=($,Z)=>{for(var Q in Z)L2($,Q,{get:Z[Q],enumerable:!0,configurable:!0,set:(X)=>Z[Q]=()=>X})};var O=($,Z)=>()=>($&&(Z=$($=0)),Z);function o1($){let Z=$??process.argv.slice(2),Q=[],X={},q=0;while(q<Z.length){let z=Z[q];if(z.startsWith("--")){let Y=z.slice(2),K=Z[q+1];if(K!==void 0&&!K.startsWith("-"))X[Y]=K,q+=2;else X[Y]=!0,q+=1}else if(z.startsWith("-")&&z.length===2){let Y=z.slice(1),K=Z[q+1];if(K!==void 0&&!K.startsWith("-"))X[Y]=K,q+=2;else X[Y]=!0,q+=1}else Q.push(z),q+=1}return{command:Q[0],subcommand:Q[1],positionals:Q.slice(2),flags:X}}function A($,Z){let Q=$.flags[Z];if(Q===void 0||Q===!0)return;return Q}function P($,Z){return Z in $.flags}function n1($,Z,Q){let X=A($,Z);if(X===void 0)throw new Error(`Missing required flag: --${Z} <${Q}>`);return X}var D0="0000000000000000000000000000000000000000000000000000000000000001",a1="0000000000000000000000000000000000000000000000000000000000000000",s0=6,t1=1e6,r1=1000000000000n,s1=5,e1=300000,$3=1e4,R0=120000,Z3=300000,e0=60000,$1=10,x0=3,Q3=600000,E0=15000,X3=115,m=".midnight",J0="wallet.json",q3="config.json",Q0=448,N0=384,z3="localnet";function i(){return!("NO_COLOR"in process.env)}function K0($,Z){if(!i())return $;return`\x1B[38;5;${Z}m${$}\x1B[0m`}function y($){if(!i())return $;return`\x1B[1m${$}\x1B[0m`}function j($){if(!i())return $;return`\x1B[2m${$}\x1B[0m`}function t($){return K0($,38)}function f($){return K0($,196)}function o($){return K0($,40)}function j0($){return K0($,226)}function F0($){return K0($,15)}function G0($){return K0($,245)}function I($,Z=J3){let Q=` ${$} `,X=Z-Q.length;if(X<=0)return y(Q);let q=Math.floor(X/2),z=X-q;return y("═".repeat(q)+Q+"═".repeat(z))}function D($=J3){return j("─".repeat($))}function H($,Z,Q=16){let X=($+":").padEnd(Q);return` ${G0(X)}${Z}`}function O0($){let Z=$<0n,Q=Z?-$:$,X=BigInt(10**s0),q=Q/X,Y=(Q%X).toString().padStart(s0,"0");return`${Z?"-":""}${q}.${Y}`}function v0($){return`${O0($)} NIGHT`}function L0($){let Z=$<0n,Q=Z?-$:$,X=10n**BigInt(Y3),q=Q/X,K=(Q%X).toString().padStart(Y3,"0").replace(/0+$/,"").padEnd(6,"0");return`${Z?"-":""}${q}.${K}`}function k0($){return`${L0($)} DUST`}function E($,Z=!1){let Q=Z&&$.length>20?$.slice(0,10)+"…"+$.slice(-8):$;return t(Q)}function y2($,Z){if(P0($).length<=Z)return[$];let X=$.split(/(\s+)/),q=[],z="",Y=0;for(let K of X){let G=P0(K).length;if(Y+G>Z&&Y>0)q.push(z),z=K.trimStart(),Y=P0(z).length;else z+=K,Y+=G}if(z.length>0)q.push(z);return q}function T2($,Z="light",Q=70){let X=Z==="heavy"?{tl:"╔",tr:"╗",bl:"╚",br:"╝",h:"═",v:"║"}:{tl:"┌",tr:"┐",bl:"└",br:"┘",h:"─",v:"│"},q=Q-4,z=[];for(let J of $){let W=J.split(`
3
+ `);for(let B of W)z.push(...y2(B,q))}let Y=Math.max(...z.map((J)=>P0(J).length)),K=Math.max(Y+2,20),G=X.tl+X.h.repeat(K)+X.tr,U=X.bl+X.h.repeat(K)+X.br,V=z.map((J)=>{let W=P0(J).length,B=K-W-2;return`${X.v} ${J}${" ".repeat(Math.max(0,B))} ${X.v}`});return[G,...V,U].join(`
4
+ `)}function K3($,Z){let X=$.split(`
5
+ `).map((z,Y)=>Y===0?f(y("Error: "))+f(z):f(z));if(Z)X.push(""),X.push(j("Suggestion: ")+Z);let q=T2(X,"heavy");if(i())return q.replace(/[╔╗╚╝═║]/g,(z)=>f(z));return q}function X0($,Z){let X=[`${o("✓")} ${$}`];if(Z)X.push(H("Transaction",t(Z)));return X.join(`
6
+ `)}var J3=60,Y3=15,P0=($)=>$.replace(/\x1b\[[0-9;]*m/g,"");var N=()=>{};function y0($){let Z=($.message??"").toLowerCase();if(Z.includes("operation cancelled")||Z.includes("operation aborted")||Z==="cancelled"||Z==="aborted")return{exitCode:7,errorCode:g.CANCELLED};if(Z.includes("wallet file not found")||Z.includes("wallet")&&Z.includes("not found"))return{exitCode:3,errorCode:g.WALLET_NOT_FOUND};if(Z.includes("missing required flag")||Z.includes("missing amount")||Z.includes("missing recipient")||Z.includes("missing config key")||Z.includes("missing or invalid subcommand")||Z.includes("unknown command")||Z.includes("cannot specify both")||Z.includes("invalid bip-39")||Z.includes("seed must be")||Z.includes("key index must be")||Z.includes("usage:"))return{exitCode:2,errorCode:g.INVALID_ARGS};if(Z.includes("proof")&&Z.includes("timeout"))return{exitCode:6,errorCode:g.PROOF_TIMEOUT};if(Z.includes("stale utxo")||Z.includes("error code 115")||Z.includes("errorcode: 115"))return{exitCode:6,errorCode:g.STALE_UTXO};if(Z.includes("no dust")||Z.includes("dust")&&(Z.includes("required")||Z.includes("available")||Z.includes("insufficient")))return{exitCode:5,errorCode:g.DUST_REQUIRED};if(Z.includes("insufficient")||Z.includes("not enough"))return{exitCode:5,errorCode:g.INSUFFICIENT_BALANCE};if(Z.includes("rejected")||Z.includes("transaction failed"))return{exitCode:6,errorCode:g.TX_REJECTED};if(Z.includes("econnrefused")||Z.includes("enotfound")||Z.includes("etimedout")||Z.includes("websocket")||Z.includes("connection refused")||Z.includes("network")&&Z.includes("error"))return{exitCode:4,errorCode:g.NETWORK_ERROR};return{exitCode:1,errorCode:g.UNKNOWN}}var g;var Z1=O(()=>{g={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",PROOF_TIMEOUT:"PROOF_TIMEOUT",DUST_REQUIRED:"DUST_REQUIRED",CANCELLED:"CANCELLED",UNKNOWN:"UNKNOWN"}});function G3(){let $=process.stderr.write;return process.stderr.write=()=>!0,()=>{process.stderr.write=$}}function X1($){Q1=$}function L($){let Z=JSON.stringify($)+`
7
+ `;if(Q1)Q1(Z);else process.stdout.write(Z)}function U3($,Z,Q){process.stdout.write(JSON.stringify({error:!0,code:Z,message:$.message,exitCode:Q})+`
8
+ `)}var Q1=null;var b0;var B3=O(()=>{b0={name:"midnight-wallet-cli",version:"0.1.9",type:"module",description:"Git-style CLI wallet for the Midnight blockchain",license:"Apache-2.0",bin:{midnight:"dist/wallet.js",mn:"dist/wallet.js","midnight-wallet-cli":"dist/wallet.js","midnight-wallet-mcp":"dist/mcp-server.js"},files:["dist"],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",prepublishOnly:"npm run build && npm run test",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit"},dependencies:{"@midnight-ntwrk/ledger-v7":"7.0.0","@midnight-ntwrk/midnight-js-network-id":"3.0.0","@midnight-ntwrk/midnight-js-types":"3.0.0","@midnight-ntwrk/wallet-sdk-abstractions":"1.0.0","@midnight-ntwrk/wallet-sdk-address-format":"3.0.0","@midnight-ntwrk/wallet-sdk-dust-wallet":"1.0.0","@midnight-ntwrk/wallet-sdk-facade":"1.0.0","@midnight-ntwrk/wallet-sdk-hd":"3.0.0","@midnight-ntwrk/wallet-sdk-shielded":"1.0.0","@midnight-ntwrk/wallet-sdk-unshielded-wallet":"1.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"}}});var V3,q0,W3;var w0=O(()=>{B3();V3=b0.name,q0=b0.version,W3=b0.description});async function R($,Z,Q){let X=[];X1((z)=>X.push(z));let q=process.stderr.write;process.stderr.write=()=>!0;try{Z.flags.json=!0,await $(Z,Q);let z=X.join("").trim();if(!z)return{};return JSON.parse(z)}finally{X1(null),process.stderr.write=q}}var H3=()=>{};import{HDWallet as I2,Roles as _2}from"@midnight-ntwrk/wallet-sdk-hd";import{createKeystore as A2,PublicKey as D2}from"@midnight-ntwrk/wallet-sdk-unshielded-wallet";import{NetworkId as q1}from"@midnight-ntwrk/wallet-sdk-abstractions";function U0($,Z,Q=0){let X=R2[Z],q=I2.fromSeed($);if(q.type!=="seedOk")throw new Error("Invalid seed for HD wallet");let z=q.hdWallet.selectAccount(0).selectRole(_2.NightExternal).deriveKeyAt(Q);if(z.type==="keyOutOfBounds")throw new Error(`Key index ${Q} out of bounds`);let Y=A2(z.key,X);return D2.fromKeyStore(Y).address}var R2;var S0=O(()=>{R2={preprod:q1.NetworkId.PreProd,preview:q1.NetworkId.Preview,undeployed:q1.NetworkId.Undeployed}});import{execSync as x2}from"child_process";function n($){return j3.includes($)}function N2($){return{...E2[$]}}function F3(){return j3}function P3($){if($.startsWith("mn_addr_preprod1"))return"preprod";if($.startsWith("mn_addr_preview1"))return"preview";if($.startsWith("mn_addr_undeployed1"))return"undeployed";return null}function v2(){try{let $=x2('docker ps --format "{{.Image}}|{{.Ports}}"',{encoding:"utf-8",timeout:5000}),Z={};for(let Q of $.trim().split(`
9
+ `)){if(!Q)continue;let[X,q]=Q.split("|"),z=(Y)=>{let K=new RegExp(`0\\.0\\.0\\.0:(\\d+)->${Y}/tcp`),G=q?.match(K);return G?parseInt(G[1],10):void 0};if(X.includes("indexer-standalone")||X.includes("indexer")){let Y=z(8088);if(Y)Z.indexerPort=Y}if(X.includes("midnight-node")){let Y=z(9944);if(Y)Z.nodePort=Y}if(X.includes("proof-server")){let Y=z(6300);if(Y)Z.proofServerPort=Y}}return Z}catch{return{}}}function O3($){let Z=N2($);if($==="undeployed"){let Q=v2();if(Q.indexerPort)Z.indexer=`http://localhost:${Q.indexerPort}/api/v3/graphql`,Z.indexerWS=`ws://localhost:${Q.indexerPort}/api/v3/graphql/ws`;if(Q.nodePort)Z.node=`ws://localhost:${Q.nodePort}`;if(Q.proofServerPort)Z.proofServer=`http://localhost:${Q.proofServerPort}`}return Z}var E2,j3;var C0=O(()=>{E2={preprod:{indexer:"https://indexer.preprod.midnight.network/api/v3/graphql",indexerWS:"wss://indexer.preprod.midnight.network/api/v3/graphql/ws",node:"wss://rpc.preprod.midnight.network",proofServer:"http://localhost:6300",networkId:"PreProd"},preview:{indexer:"https://indexer.preview.midnight.network/api/v3/graphql",indexerWS:"wss://indexer.preview.midnight.network/api/v3/graphql/ws",node:"wss://rpc.preview.midnight.network",proofServer:"http://localhost:6300",networkId:"Preview"},undeployed:{indexer:"http://localhost:8088/api/v3/graphql",indexerWS:"ws://localhost:8088/api/v3/graphql/ws",node:"ws://localhost:9944",proofServer:"http://localhost:6300",networkId:"Undeployed"}},j3=["preprod","preview","undeployed"]});import*as a from"fs";import*as z1 from"path";import{homedir as k2}from"os";function L3($){return $??z1.join(k2(),m)}function y3($){return z1.join(L3($),q3)}function b2($){let Z=L3($);if(!a.existsSync(Z))a.mkdirSync(Z,{recursive:!0,mode:Q0})}function h0($){let Z=y3($);if(!a.existsSync(Z))return{...f0};let Q;try{Q=a.readFileSync(Z,"utf-8")}catch{return{...f0}}let X;try{X=JSON.parse(Q)}catch{return{...f0}}return{network:X.network&&n(X.network)?X.network:f0.network}}function w2($,Z){b2(Z);let Q=y3(Z);a.writeFileSync(Q,JSON.stringify($,null,2)+`
10
+ `,{mode:N0})}function T3($,Z){let Q=h0(Z);if($==="network")return Q.network;throw new Error(`Unknown config key: "${$}"
11
+ Valid keys: ${Y1.join(", ")}`)}function M3($,Z,Q){let X=h0(Q);if($==="network"){if(!n(Z))throw new Error(`Invalid network: "${Z}"
12
+ Valid networks: preprod, preview, undeployed`);X.network=Z}else throw new Error(`Unknown config key: "${$}"
13
+ Valid keys: ${Y1.join(", ")}`);w2(X,Q)}function J1(){return Y1}var f0,Y1;var K1=O(()=>{C0();f0={network:"undeployed"},Y1=["network"]});function z0($){let Z=A($.args,"network");if(Z!==void 0){if(!n(Z))throw new Error(`Invalid network: "${Z}"
14
+ Valid networks: ${F3().join(", ")}`);return Z}if($.walletNetwork&&n($.walletNetwork))return $.walletNetwork;if($.address){let X=P3($.address);if(X)return X}let Q=h0($.configDir);if(Q.network&&n(Q.network))return Q.network;return"undeployed"}function r($){let Z=z0($),Q=O3(Z);return{name:Z,config:Q}}var s=O(()=>{C0();K1()});import*as h from"fs";import*as e from"path";import{homedir as S2}from"os";function I3(){return e.join(S2(),m)}function _3(){return e.join(I3(),J0)}function C2(){let $=I3();if(!h.existsSync($))h.mkdirSync($,{recursive:!0,mode:Q0})}function d($){let Z=$?e.resolve($):_3();if(!h.existsSync(Z))throw new Error(`Wallet file not found: ${Z}
15
+ Generate a wallet first: midnight generate --network <name>`);let Q;try{Q=h.readFileSync(Z,"utf-8")}catch(q){throw new Error(`Failed to read wallet file: ${Z}
16
+ ${q.message}`)}let X;try{X=JSON.parse(Q)}catch{throw new Error(`Invalid JSON in wallet file: ${Z}`)}if(!X.seed||!X.network||!X.address||!X.createdAt){let q=["seed","network","address","createdAt"].filter((z)=>!X[z]);throw new Error(`Wallet file is missing required fields (${q.join(", ")}): ${Z}`)}if(!/^[0-9a-fA-F]+$/.test(X.seed))throw new Error(`Invalid seed format in wallet file (expected hex string): ${Z}`);if(!n(X.network))throw new Error(`Invalid network "${X.network}" in wallet file: ${Z}
17
+ Valid networks: preprod, preview, undeployed`);return X}function A3($,Z){let Q=Z?e.resolve(Z):_3();if(!Z)C2();else{let X=e.dirname(Q);if(!h.existsSync(X))h.mkdirSync(X,{recursive:!0,mode:Q0})}return h.writeFileSync(Q,JSON.stringify($,null,2)+`
18
+ `,{mode:N0}),Q}var Y0=O(()=>{C0()});var G1={};S(G1,{default:()=>E3});import*as x3 from"fs";import*as p0 from"path";import{homedir as f2}from"os";import{generateMnemonic as h2,mnemonicToSeedSync as D3,validateMnemonic as p2}from"@scure/bip39";import{wordlist as R3}from"@scure/bip39/wordlists/english.js";async function E3($){let Z=z0({args:$}),Q=A($,"output"),X=A($,"seed"),q=A($,"mnemonic");if(X!==void 0&&q!==void 0)throw new Error("Cannot specify both --seed and --mnemonic. Use one or the other.");let z=Q?p0.resolve(Q):p0.join(f2(),m,J0);if(x3.existsSync(z)&&!P($,"force"))throw new Error(`Wallet file already exists: ${z}
19
+ Use --force to overwrite, or --output <file> to save to a different path.`);let Y,K;if(X!==void 0){let J=X.replace(/^0x/,"");if(J.length!==64||!/^[0-9a-fA-F]+$/.test(J))throw new Error("Seed must be a 64-character hex string (32 bytes)");Y=Buffer.from(J,"hex")}else if(q!==void 0){if(!p2(q,R3))throw new Error("Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.");K=q,Y=Buffer.from(D3(K).slice(0,32))}else K=h2(R3,256),Y=Buffer.from(D3(K).slice(0,32));let G=U0(Y,Z),U={seed:Y.toString("hex"),network:Z,address:G,createdAt:new Date().toISOString()};if(K)U.mnemonic=K;let V=A3(U,Q);if(P($,"json")){let J={address:G,network:Z,seed:Y.toString("hex"),file:V,createdAt:U.createdAt};if(K)J.mnemonic=K;L(J);return}if(process.stdout.write(G+`
20
+ `),process.stderr.write(`
21
+ `+I("Wallet Generated")+`
22
+
23
+ `),process.stderr.write(H("Network",Z)+`
24
+ `),process.stderr.write(H("Address",E(G))+`
25
+ `),process.stderr.write(H("File",V)+`
26
+ `),process.stderr.write(`
27
+ `),K)process.stderr.write(j0(y(" MNEMONIC (save securely!):"))+`
28
+ `),process.stderr.write(` ${K}
29
+
30
+ `);process.stderr.write(j0(y(" SEED (hex):"))+`
31
+ `),process.stderr.write(` ${Y.toString("hex")}
32
+
33
+ `),process.stderr.write(D()+`
34
+ `),process.stderr.write(j(" Next: midnight info | midnight balance")+`
35
+
36
+ `),process.stderr.write(o("✓")+` Wallet saved
37
+ `)}var U1=O(()=>{S0();s();Y0();N()});var B1={};S(B1,{default:()=>N3});import*as u0 from"path";import{homedir as u2}from"os";async function N3($){let Z=A($,"wallet"),Q=d(Z),X=Z?u0.resolve(Z):u0.join(u2(),m,J0);if(P($,"json")){L({address:Q.address,network:Q.network,createdAt:Q.createdAt,file:X});return}process.stdout.write(Q.address+`
38
+ `),process.stderr.write(`
39
+ `+I("Wallet Info")+`
40
+
41
+ `),process.stderr.write(H("Address",E(Q.address))+`
42
+ `),process.stderr.write(H("Network",Q.network)+`
43
+ `),process.stderr.write(H("Created",Q.createdAt)+`
44
+ `),process.stderr.write(H("File",X)+`
45
+ `),process.stderr.write(`
46
+ `+D()+`
47
+
48
+ `)}var V1=O(()=>{Y0();N();N()});import c2 from"ws";function v3($,Z,Q){return new Promise((X,q)=>{let z=new c2(Z,["graphql-transport-ws"]),Y=new Map,K=0,G=0,U=0,V=!1,J=!1,W,B=()=>{let _=new Map,T=0;for(let k of Y.values())if(!k.spent){T++;let C=_.get(k.tokenType)??0n;_.set(k.tokenType,C+k.value)}return{balances:_,utxoCount:T,txCount:K,highestTxId:G}},F=()=>{clearTimeout(W)},M=()=>{if(!J&&V&&(G===0||U>=G))J=!0,F(),z.send(JSON.stringify({id:"1",type:"complete"})),z.close(),X(B())};z.on("open",()=>{z.send(JSON.stringify({type:"connection_init"}))}),z.on("message",(_)=>{let T=JSON.parse(_.toString());switch(T.type){case"connection_ack":z.send(JSON.stringify({id:"1",type:"subscribe",payload:{query:m2,variables:{address:$}}}));break;case"next":{if(T.payload?.errors){let C=T.payload.errors[0]?.message||"Unknown GraphQL error";if(!J)J=!0,F(),z.close(),q(new Error(`GraphQL error: ${C}`));return}let k=T.payload?.data?.unshieldedTransactions;if(!k)return;if(k.__typename==="UnshieldedTransaction"){K++;let C=k;U=Math.max(U,C.transaction.id);for(let c of C.createdUtxos){let b=`${c.intentHash}:${c.outputIndex}`;Y.set(b,{value:BigInt(c.value),tokenType:c.tokenType,spent:!1})}for(let c of C.spentUtxos){let b=`${c.intentHash}:${c.outputIndex}`,$0=Y.get(b);if($0)$0.spent=!0}if(Q)Q(U,G);M()}else if(k.__typename==="UnshieldedTransactionsProgress")G=k.highestTransactionId,V=!0,M();break}case"error":if(!J)J=!0,F(),z.close(),q(new Error(`GraphQL subscription error: ${JSON.stringify(T.payload)}`));break;case"complete":break}}),z.on("error",(_)=>{if(!J)J=!0,F(),q(new Error(`WebSocket connection failed: ${_.message}`))}),z.on("close",()=>{if(!J)J=!0,F(),q(new Error(`Indexer closed the connection before balance sync completed. Indexer: ${Z}`))}),W=setTimeout(()=>{if(!J)J=!0,z.close(),q(new Error(`Balance check timed out after ${e0/1000}s. Indexer: ${Z}`))},e0)})}function T0($){return $===a1}var m2=`
986
49
  subscription UnshieldedTransactions($address: UnshieldedAddress!) {
987
50
  unshieldedTransactions(address: $address) {
988
51
  __typename
@@ -996,1268 +59,138 @@ var SUBSCRIPTION_QUERY = `
996
59
  }
997
60
  }
998
61
  }
999
- `;
1000
- var init_balance_subscription = () => {
1001
- };
1002
-
1003
- // src/ui/spinner.ts
1004
- function start(message) {
1005
- if (!isColorEnabled()) {
1006
- process.stderr.write(`⠋ ${message}`);
1007
- return {
1008
- update(msg) {
1009
- process.stderr.write(`\r⠋ ${msg}`);
1010
- },
1011
- stop(finalMessage) {
1012
- const final = finalMessage ?? message;
1013
- process.stderr.write(`\r✓ ${final}
1014
- `);
1015
- }
1016
- };
1017
- }
1018
- let frameIndex = 0;
1019
- let currentMessage = message;
1020
- const render = () => {
1021
- const frame = teal(BRAILLE_FRAMES[frameIndex]);
1022
- process.stderr.write(`\r${frame} ${currentMessage}\x1B[K`);
1023
- frameIndex = (frameIndex + 1) % BRAILLE_FRAMES.length;
1024
- };
1025
- render();
1026
- const timer = setInterval(render, FRAME_INTERVAL_MS);
1027
- return {
1028
- update(msg) {
1029
- currentMessage = msg;
1030
- },
1031
- stop(finalMessage) {
1032
- clearInterval(timer);
1033
- const final = finalMessage ?? currentMessage;
1034
- process.stderr.write(`\r\x1B[32m✓\x1B[0m ${final}\x1B[K
1035
- `);
1036
- }
1037
- };
1038
- }
1039
- var BRAILLE_FRAMES, FRAME_INTERVAL_MS = 80;
1040
- var init_spinner = __esm(() => {
1041
- BRAILLE_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
1042
- });
1043
-
1044
- // src/commands/balance.ts
1045
- var exports_balance = {};
1046
- __export(exports_balance, {
1047
- default: () => balanceCommand
1048
- });
1049
- async function balanceCommand(args) {
1050
- let address;
1051
- let walletNetwork;
1052
- if (args.subcommand) {
1053
- address = args.subcommand;
1054
- } else {
1055
- const walletPath = getFlag(args, "wallet");
1056
- const config = loadWalletConfig(walletPath);
1057
- address = config.address;
1058
- walletNetwork = config.network;
1059
- }
1060
- if (!address) {
1061
- throw new Error("No address provided and no wallet file found.");
1062
- }
1063
- const { name: networkName, config: networkConfig } = resolveNetwork({
1064
- args,
1065
- walletNetwork,
1066
- address
1067
- });
1068
- const indexerWsOverride = getFlag(args, "indexer-ws");
1069
- const indexerWS = indexerWsOverride ?? networkConfig.indexerWS;
1070
- const spinner = start(`Checking balance on ${networkName}...`);
1071
- try {
1072
- const result = await checkBalance(address, indexerWS, (current, highest) => {
1073
- if (highest > 0) {
1074
- const pct = Math.round(current / highest * 100);
1075
- spinner.update(`Syncing transactions... ${pct}%`);
1076
- }
1077
- });
1078
- spinner.stop(`Synced ${result.txCount} transactions`);
1079
- if (hasFlag(args, "json")) {
1080
- const balances = {};
1081
- for (const [tokenType, amount] of result.balances) {
1082
- const key = isNativeToken(tokenType) ? "NIGHT" : tokenType;
1083
- balances[key] = isNativeToken(tokenType) ? toNight(amount) : amount.toString();
1084
- }
1085
- writeJsonResult({
1086
- address,
1087
- network: networkName,
1088
- balances,
1089
- utxoCount: result.utxoCount,
1090
- txCount: result.txCount
1091
- });
1092
- return;
1093
- }
1094
- if (result.balances.size === 0) {
1095
- process.stdout.write(`0
1096
- `);
1097
- } else {
1098
- for (const [tokenType, amount] of result.balances) {
1099
- if (isNativeToken(tokenType)) {
1100
- process.stdout.write(`NIGHT=${amount}
1101
- `);
1102
- } else {
1103
- process.stdout.write(`${tokenType}=${amount}
1104
- `);
1105
- }
1106
- }
1107
- }
1108
- process.stderr.write(`
1109
- ` + header("Balance") + `
1110
-
1111
- `);
1112
- process.stderr.write(keyValue("Address", formatAddress(address)) + `
1113
- `);
1114
- process.stderr.write(keyValue("Network", networkName) + `
1115
- `);
1116
- process.stderr.write(keyValue("UTXOs", result.utxoCount.toString()) + `
1117
- `);
1118
- process.stderr.write(keyValue("Transactions", result.txCount.toString()) + `
1119
- `);
1120
- process.stderr.write(`
1121
- `);
1122
- if (result.balances.size === 0) {
1123
- process.stderr.write(` ${dim("No balance found")}
1124
- `);
1125
- } else {
1126
- for (const [tokenType, amount] of result.balances) {
1127
- if (isNativeToken(tokenType)) {
1128
- process.stderr.write(keyValue("NIGHT", bold(formatNight(amount))) + `
1129
- `);
1130
- } else {
1131
- const shortType = tokenType.slice(0, 8) + "…" + tokenType.slice(-8);
1132
- process.stderr.write(keyValue(`Token ${shortType}`, bold(amount.toString())) + `
1133
- `);
1134
- }
1135
- }
1136
- }
1137
- process.stderr.write(`
1138
- ` + divider() + `
1139
-
1140
- `);
1141
- } catch (err) {
1142
- spinner.stop("Failed");
1143
- throw err;
1144
- }
1145
- }
1146
- var init_balance = __esm(() => {
1147
- init_wallet_config();
1148
- init_resolve_network();
1149
- init_balance_subscription();
1150
- init_format();
1151
- init_spinner();
1152
- });
1153
-
1154
- // src/commands/address.ts
1155
- var exports_address = {};
1156
- __export(exports_address, {
1157
- default: () => addressCommand
1158
- });
1159
- async function addressCommand(args) {
1160
- const seedHex = requireFlag(args, "seed", "hex").replace(/^0x/, "");
1161
- if (seedHex.length !== 64 || !/^[0-9a-fA-F]+$/.test(seedHex)) {
1162
- throw new Error("Seed must be a 64-character hex string (32 bytes)");
1163
- }
1164
- const indexStr = getFlag(args, "index");
1165
- const keyIndex = indexStr !== undefined ? parseInt(indexStr, 10) : 0;
1166
- if (isNaN(keyIndex) || keyIndex < 0 || !Number.isInteger(Number(indexStr ?? "0"))) {
1167
- throw new Error("Key index must be a non-negative integer");
1168
- }
1169
- const seedBuffer = Buffer.from(seedHex, "hex");
1170
- const networkName = resolveNetworkName({ args });
1171
- const address = deriveUnshieldedAddress(seedBuffer, networkName, keyIndex);
1172
- const derivationPath = `m/44'/2400'/0'/NightExternal/${keyIndex}`;
1173
- if (hasFlag(args, "json")) {
1174
- writeJsonResult({
1175
- address,
1176
- network: networkName,
1177
- index: keyIndex,
1178
- path: derivationPath
1179
- });
1180
- return;
1181
- }
1182
- process.stdout.write(address + `
1183
- `);
1184
- process.stderr.write(`
1185
- `);
1186
- process.stderr.write(keyValue("Network", networkName) + `
1187
- `);
1188
- process.stderr.write(keyValue("Index", keyIndex.toString()) + `
1189
- `);
1190
- process.stderr.write(keyValue("Address", formatAddress(address)) + `
1191
- `);
1192
- process.stderr.write(keyValue("Path", dim(derivationPath)) + `
1193
- `);
1194
- process.stderr.write(divider() + `
1195
-
1196
- `);
1197
- }
1198
- var init_address = __esm(() => {
1199
- init_derive_address();
1200
- init_resolve_network();
1201
- init_format();
1202
- });
1203
-
1204
- // src/commands/genesis-address.ts
1205
- var exports_genesis_address = {};
1206
- __export(exports_genesis_address, {
1207
- default: () => genesisAddressCommand
1208
- });
1209
- async function genesisAddressCommand(args) {
1210
- const networkName = resolveNetworkName({ args });
1211
- const seedBuffer = Buffer.from(GENESIS_SEED, "hex");
1212
- const address = deriveUnshieldedAddress(seedBuffer, networkName);
1213
- if (hasFlag(args, "json")) {
1214
- writeJsonResult({ address, network: networkName });
1215
- return;
1216
- }
1217
- process.stdout.write(address + `
1218
- `);
1219
- process.stderr.write(`
1220
- `);
1221
- process.stderr.write(keyValue("Network", networkName) + `
1222
- `);
1223
- process.stderr.write(keyValue("Address", formatAddress(address)) + `
1224
- `);
1225
- process.stderr.write(keyValue("Seed", dim("0x01 (genesis)")) + `
1226
- `);
1227
- process.stderr.write(divider() + `
1228
-
1229
- `);
1230
- }
1231
- var init_genesis_address = __esm(() => {
1232
- init_derive_address();
1233
- init_resolve_network();
1234
- init_format();
1235
- });
1236
-
1237
- // src/commands/inspect-cost.ts
1238
- var exports_inspect_cost = {};
1239
- __export(exports_inspect_cost, {
1240
- default: () => inspectCostCommand
1241
- });
1242
- import * as ledger from "@midnight-ntwrk/ledger-v7";
1243
- function probeDimension(params, dimension, probeValue) {
1244
- const cost = {
1245
- readTime: 0n,
1246
- computeTime: 0n,
1247
- blockUsage: 0n,
1248
- bytesWritten: 0n,
1249
- bytesChurned: 0n
1250
- };
1251
- cost[dimension] = probeValue;
1252
- const normalized = params.normalizeFullness(cost);
1253
- const normalizedValue = normalized[dimension];
1254
- return Math.round(Number(probeValue) / normalizedValue);
1255
- }
1256
- function deriveBlockLimits(params) {
1257
- return {
1258
- readTime: probeDimension(params, "readTime", 1000000000n),
1259
- computeTime: probeDimension(params, "computeTime", 1000000000n),
1260
- blockUsage: probeDimension(params, "blockUsage", 10000n),
1261
- bytesWritten: probeDimension(params, "bytesWritten", 10000n),
1262
- bytesChurned: probeDimension(params, "bytesChurned", 1000000n)
1263
- };
1264
- }
1265
- async function inspectCostCommand(args) {
1266
- const params = ledger.LedgerParameters.initialParameters();
1267
- const limits = deriveBlockLimits(params);
1268
- if (hasFlag(args, "json")) {
1269
- writeJsonResult(limits);
1270
- return;
1271
- }
1272
- for (const [dimension, value] of Object.entries(limits)) {
1273
- process.stdout.write(`${dimension}=${value}
1274
- `);
1275
- }
1276
- process.stderr.write(`
1277
- ` + header("Block Limits") + `
1278
-
1279
- `);
1280
- process.stderr.write(dim(" Derived from LedgerParameters.initialParameters()") + `
1281
-
1282
- `);
1283
- for (const [dimension, value] of Object.entries(limits)) {
1284
- const unit = UNITS[dimension] ?? "";
1285
- process.stderr.write(keyValue(dimension, `${bold(value.toLocaleString())} ${dim(unit)}`) + `
1286
- `);
1287
- }
1288
- process.stderr.write(`
1289
- ` + divider() + `
1290
- `);
1291
- process.stderr.write(dim(" bytesWritten is typically the tightest constraint") + `
1292
- `);
1293
- process.stderr.write(dim(" for large contract deployments.") + `
1294
-
1295
- `);
1296
- }
1297
- var UNITS;
1298
- var init_inspect_cost = __esm(() => {
1299
- init_format();
1300
- UNITS = {
1301
- readTime: "picoseconds",
1302
- computeTime: "picoseconds",
1303
- blockUsage: "bytes",
1304
- bytesWritten: "bytes",
1305
- bytesChurned: "bytes"
1306
- };
1307
- });
1308
-
1309
- // src/lib/derivation.ts
1310
- import { HDWallet as HDWallet2, Roles as Roles2 } from "@midnight-ntwrk/wallet-sdk-hd";
1311
- function deriveKey(seedBuffer, role) {
1312
- const hdResult = HDWallet2.fromSeed(seedBuffer);
1313
- if (hdResult.type !== "seedOk") {
1314
- throw new Error("Invalid seed for HD wallet");
1315
- }
1316
- const derivation = hdResult.hdWallet.selectAccount(0).selectRole(role).deriveKeyAt(0);
1317
- if (derivation.type === "keyOutOfBounds") {
1318
- throw new Error("Key derivation out of bounds");
1319
- }
1320
- return derivation.key;
1321
- }
1322
- function deriveShieldedSeed(seedBuffer) {
1323
- return deriveKey(seedBuffer, Roles2.Zswap);
1324
- }
1325
- function deriveUnshieldedSeed(seedBuffer) {
1326
- return deriveKey(seedBuffer, Roles2.NightExternal);
1327
- }
1328
- function deriveDustSeed(seedBuffer) {
1329
- return deriveKey(seedBuffer, Roles2.Dust);
1330
- }
1331
- var init_derivation = () => {
1332
- };
1333
-
1334
- // src/lib/facade.ts
1335
- import { ShieldedWallet } from "@midnight-ntwrk/wallet-sdk-shielded";
1336
- import {
1337
- UnshieldedWallet,
1338
- createKeystore as createKeystore2,
1339
- PublicKey as PublicKey2,
1340
- InMemoryTransactionHistoryStorage
1341
- } from "@midnight-ntwrk/wallet-sdk-unshielded-wallet";
1342
- import { DustWallet } from "@midnight-ntwrk/wallet-sdk-dust-wallet";
1343
- import { WalletFacade } from "@midnight-ntwrk/wallet-sdk-facade";
1344
- import * as ledger2 from "@midnight-ntwrk/ledger-v7";
1345
- import { NetworkId as NetworkId2 } from "@midnight-ntwrk/wallet-sdk-abstractions";
1346
- import * as rx from "rxjs";
1347
- function buildFacade(seedBuffer, networkConfig) {
1348
- const networkId = NETWORK_ID_MAP2[networkConfig.networkId];
1349
- if (networkId === undefined) {
1350
- throw new Error(`Unknown networkId: ${networkConfig.networkId}`);
1351
- }
1352
- const shieldedSeed = deriveShieldedSeed(seedBuffer);
1353
- const unshieldedSeed = deriveUnshieldedSeed(seedBuffer);
1354
- const dustSeed = deriveDustSeed(seedBuffer);
1355
- const zswapSecretKeys = ledger2.ZswapSecretKeys.fromSeed(shieldedSeed);
1356
- const dustSecretKey = ledger2.DustSecretKey.fromSeed(dustSeed);
1357
- const keystore = createKeystore2(unshieldedSeed, networkId);
1358
- const shieldedConfig = {
1359
- networkId,
1360
- indexerClientConnection: {
1361
- indexerHttpUrl: networkConfig.indexer,
1362
- indexerWsUrl: networkConfig.indexerWS
1363
- },
1364
- provingServerUrl: new URL(networkConfig.proofServer),
1365
- relayURL: new URL(networkConfig.node)
1366
- };
1367
- const unshieldedConfig = {
1368
- networkId,
1369
- indexerClientConnection: {
1370
- indexerHttpUrl: networkConfig.indexer,
1371
- indexerWsUrl: networkConfig.indexerWS
1372
- },
1373
- txHistoryStorage: new InMemoryTransactionHistoryStorage
1374
- };
1375
- const dustConfig = {
1376
- networkId,
1377
- costParameters: {
1378
- additionalFeeOverhead: DUST_COST_OVERHEAD,
1379
- feeBlocksMargin: DUST_FEE_BLOCKS_MARGIN
1380
- },
1381
- indexerClientConnection: {
1382
- indexerHttpUrl: networkConfig.indexer,
1383
- indexerWsUrl: networkConfig.indexerWS
1384
- },
1385
- provingServerUrl: new URL(networkConfig.proofServer),
1386
- relayURL: new URL(networkConfig.node)
1387
- };
1388
- const shieldedWallet = ShieldedWallet(shieldedConfig).startWithSecretKeys(zswapSecretKeys);
1389
- const unshieldedWallet = UnshieldedWallet(unshieldedConfig).startWithPublicKey(PublicKey2.fromKeyStore(keystore));
1390
- const dustWallet = DustWallet(dustConfig).startWithSecretKey(dustSecretKey, ledger2.LedgerParameters.initialParameters().dust);
1391
- const facade = new WalletFacade(shieldedWallet, unshieldedWallet, dustWallet);
1392
- return { facade, keystore, zswapSecretKeys, dustSecretKey };
1393
- }
1394
- async function startAndSyncFacade(bundle, onProgress) {
1395
- const { facade, zswapSecretKeys, dustSecretKey } = bundle;
1396
- await facade.start(zswapSecretKeys, dustSecretKey);
1397
- return rx.firstValueFrom(facade.state().pipe(rx.tap((state) => {
1398
- if (onProgress) {
1399
- const progress = state.unshielded.progress;
1400
- if (progress) {
1401
- onProgress(Number(progress.appliedId), Number(progress.highestTransactionId));
1402
- }
1403
- }
1404
- }), rx.filter((state) => state.isSynced), rx.timeout(SYNC_TIMEOUT_MS)));
1405
- }
1406
- async function quickSync(bundle) {
1407
- return rx.firstValueFrom(bundle.facade.state().pipe(rx.filter((state) => state.isSynced), rx.timeout(PRE_SEND_SYNC_TIMEOUT_MS)));
1408
- }
1409
- async function stopFacade(bundle) {
1410
- await bundle.facade.stop();
1411
- }
1412
- function suppressSdkTransientErrors(onWarning) {
1413
- const rejectionHandler = (reason) => {
1414
- const tag = reason?._tag;
1415
- if (typeof tag === "string" && tag.startsWith("Wallet.")) {
1416
- const msg = reason?.message ?? "transient error";
1417
- onWarning?.(tag, msg);
1418
- return;
1419
- }
1420
- originalConsoleError("Unhandled rejection:", reason);
1421
- process.exit(1);
1422
- };
1423
- const originalConsoleError = console.error;
1424
- console.error = (...args) => {
1425
- const firstArg = args[0];
1426
- if (typeof firstArg === "object" && firstArg?._tag?.startsWith("Wallet.")) {
1427
- onWarning?.(firstArg._tag, firstArg?.message ?? "transient error");
1428
- return;
1429
- }
1430
- if (typeof firstArg === "string" && firstArg.startsWith("Wallet.")) {
1431
- onWarning?.("Wallet.Sync", "transient error");
1432
- return;
1433
- }
1434
- originalConsoleError(...args);
1435
- };
1436
- process.on("unhandledRejection", rejectionHandler);
1437
- return () => {
1438
- process.removeListener("unhandledRejection", rejectionHandler);
1439
- console.error = originalConsoleError;
1440
- };
1441
- }
1442
- var NETWORK_ID_MAP2;
1443
- var init_facade = __esm(() => {
1444
- init_derivation();
1445
- NETWORK_ID_MAP2 = {
1446
- PreProd: NetworkId2.NetworkId.PreProd,
1447
- Preview: NetworkId2.NetworkId.Preview,
1448
- Undeployed: NetworkId2.NetworkId.Undeployed
1449
- };
1450
- });
1451
-
1452
- // src/lib/transfer.ts
1453
- import * as ledger3 from "@midnight-ntwrk/ledger-v7";
1454
- import { MidnightBech32m, UnshieldedAddress } from "@midnight-ntwrk/wallet-sdk-address-format";
1455
- import { NetworkId as NetworkId3 } from "@midnight-ntwrk/wallet-sdk-abstractions";
1456
- import * as rx2 from "rxjs";
1457
- function nightToMicro(amountNight) {
1458
- if (amountNight <= 0) {
1459
- throw new Error("Amount must be greater than 0");
1460
- }
1461
- if (!Number.isFinite(amountNight)) {
1462
- throw new Error("Amount must be a finite number");
1463
- }
1464
- const str = amountNight.toFixed(6);
1465
- const [whole, frac] = str.split(".");
1466
- const microStr = whole + (frac ?? "").padEnd(6, "0");
1467
- const micro = BigInt(microStr);
1468
- if (micro <= 0n) {
1469
- throw new Error("Amount too small — minimum is 0.000001 NIGHT");
1470
- }
1471
- return micro;
1472
- }
1473
- function parseAmount(amountStr) {
1474
- const amount = Number(amountStr);
1475
- if (Number.isNaN(amount) || !Number.isFinite(amount)) {
1476
- throw new Error(`Invalid amount: "${amountStr}" — must be a positive number`);
1477
- }
1478
- if (amount <= 0) {
1479
- throw new Error(`Invalid amount: "${amountStr}" — must be greater than 0`);
1480
- }
1481
- return amount;
1482
- }
1483
- function validateRecipientAddress(address, networkConfig) {
1484
- const networkId = NETWORK_ID_MAP3[networkConfig.networkId];
1485
- if (networkId === undefined) {
1486
- throw new Error(`Unknown networkId: ${networkConfig.networkId}`);
1487
- }
1488
- try {
1489
- MidnightBech32m.parse(address).decode(UnshieldedAddress, networkId);
1490
- } catch (err) {
1491
- throw new Error(`Invalid recipient address: ${err.message}
1492
- ` + `Expected a bech32m address for network "${networkConfig.networkId}"`);
1493
- }
1494
- }
1495
- function isTransactionRejectedError(err) {
1496
- let current = err;
1497
- while (current) {
1498
- const msg = String(current?.message ?? "").toLowerCase();
1499
- if (msg.includes("submission error"))
1500
- return true;
1501
- if (msg.includes("transaction") && msg.includes("invalid"))
1502
- return true;
1503
- if (msg.includes("138"))
1504
- return true;
1505
- const tag = current?._tag;
1506
- if (tag === "TransactionInvalidError" || tag === "SubmissionError")
1507
- return true;
1508
- current = current.cause;
1509
- }
1510
- return false;
1511
- }
1512
- function formatElapsed(ms) {
1513
- const totalSeconds = Math.round(ms / 1000);
1514
- if (totalSeconds < 60)
1515
- return `${totalSeconds}s`;
1516
- const minutes = Math.floor(totalSeconds / 60);
1517
- const seconds = totalSeconds % 60;
1518
- return `${minutes}m ${seconds}s`;
1519
- }
1520
- async function submitDustRegistration(bundle, dustUtxos, dustReceiverAddress) {
1521
- const ttl = new Date(Date.now() + TX_TTL_MINUTES * 60 * 1000);
1522
- await bundle.facade.dust.waitForSyncedState();
1523
- const unprovenTx = await bundle.facade.dust.createDustGenerationTransaction(new Date, ttl, dustUtxos, bundle.keystore.getPublicKey(), dustReceiverAddress);
1524
- const intent = unprovenTx.intents?.get(1);
1525
- if (!intent) {
1526
- throw new Error("Dust generation intent not found on transaction");
1527
- }
1528
- const signature = bundle.keystore.signData(intent.signatureData(1));
1529
- const signedTx = await bundle.facade.dust.addDustGenerationSignature(unprovenTx, signature);
1530
- const finalized = await bundle.facade.finalizeTransaction(signedTx);
1531
- return await bundle.facade.submitTransaction(finalized);
1532
- }
1533
- async function registerNightUtxos(bundle, dustUtxos, dustReceiverAddress, onStatus) {
1534
- const startTime = Date.now();
1535
- const deadline = startTime + DUST_REGISTRATION_TIMEOUT_MS;
1536
- let lastError;
1537
- const originalWarn = console.warn;
1538
- const originalError = console.error;
1539
- const hasRpcNoise = (args) => args.some((a) => String(a).includes("RPC-CORE"));
1540
- const suppressRpcNoise = () => {
1541
- console.warn = (...args) => {
1542
- if (hasRpcNoise(args))
1543
- return;
1544
- originalWarn(...args);
1545
- };
1546
- console.error = (...args) => {
1547
- if (hasRpcNoise(args))
1548
- return;
1549
- originalError(...args);
1550
- };
1551
- };
1552
- const restoreConsole = () => {
1553
- console.warn = originalWarn;
1554
- console.error = originalError;
1555
- };
1556
- suppressRpcNoise();
1557
- try {
1558
- while (Date.now() < deadline) {
1559
- try {
1560
- return await submitDustRegistration(bundle, dustUtxos, dustReceiverAddress);
1561
- } catch (err) {
1562
- lastError = err;
1563
- if (isTransactionRejectedError(err) && Date.now() + DUST_REGISTRATION_RETRY_DELAY_MS < deadline) {
1564
- const elapsed = formatElapsed(Date.now() - startTime);
1565
- onStatus?.(`Waiting for dust generation capacity (${elapsed} elapsed, ~5 min on fresh wallets)...`);
1566
- await new Promise((resolve4) => setTimeout(resolve4, DUST_REGISTRATION_RETRY_DELAY_MS));
1567
- continue;
1568
- }
1569
- throw err;
1570
- }
1571
- }
1572
- throw lastError ?? new Error("Dust registration timed out");
1573
- } finally {
1574
- restoreConsole();
1575
- }
1576
- }
1577
- async function ensureDust(bundle, onDust) {
1578
- const state = await rx2.firstValueFrom(bundle.facade.state().pipe(rx2.filter((s) => s.isSynced)));
1579
- const nightUtxos = state.unshielded.availableCoins.filter((coin) => coin.meta?.registeredForDustGeneration !== true);
1580
- if (nightUtxos.length > 0) {
1581
- onDust?.(`Registering ${nightUtxos.length} UTXO(s) for dust generation...`);
1582
- const dustUtxos = nightUtxos.map((coin) => ({
1583
- ...coin.utxo,
1584
- ctime: new Date(coin.meta.ctime)
1585
- }));
1586
- await registerNightUtxos(bundle, dustUtxos, state.dust.dustAddress, onDust);
1587
- } else if (state.dust.availableCoins.length > 0) {
1588
- onDust?.("Dust available");
1589
- return;
1590
- } else {
1591
- onDust?.("UTXOs already registered, waiting for dust generation...");
1592
- }
1593
- onDust?.("Waiting for dust tokens...");
1594
- await rx2.firstValueFrom(bundle.facade.state().pipe(rx2.throttleTime(5000), rx2.filter((s) => s.isSynced), rx2.filter((s) => s.dust.walletBalance(new Date) > 0n), rx2.timeout(DUST_TIMEOUT_MS)));
1595
- onDust?.("Dust available");
1596
- }
1597
- async function buildAndSubmitTransfer(bundle, recipientAddress, amount, onProving, onSubmitting, onDust) {
1598
- let lastError;
1599
- for (let attempt = 1;attempt <= MAX_RETRY_ATTEMPTS; attempt++) {
1600
- try {
1601
- if (attempt > 1) {
1602
- await quickSync(bundle);
1603
- }
1604
- const ttl = new Date(Date.now() + TX_TTL_MINUTES * 60 * 1000);
1605
- const unprovenRecipe = await bundle.facade.transferTransaction([
1606
- {
1607
- type: "unshielded",
1608
- outputs: [
1609
- {
1610
- amount,
1611
- receiverAddress: recipientAddress,
1612
- type: ledger3.unshieldedToken().raw
1613
- }
1614
- ]
1615
- }
1616
- ], { shieldedSecretKeys: bundle.zswapSecretKeys, dustSecretKey: bundle.dustSecretKey }, { ttl, payFees: true });
1617
- const signedRecipe = await bundle.facade.signRecipe(unprovenRecipe, (payload) => bundle.keystore.signData(payload));
1618
- onProving?.();
1619
- const finalizedTx = await Promise.race([
1620
- bundle.facade.finalizeRecipe(signedRecipe),
1621
- new Promise((_, reject) => {
1622
- setTimeout(() => reject(new Error("ZK proof generation timed out")), PROOF_TIMEOUT_MS);
1623
- })
1624
- ]);
1625
- onSubmitting?.();
1626
- const txHash = await bundle.facade.submitTransaction(finalizedTx);
1627
- return txHash;
1628
- } catch (err) {
1629
- lastError = err;
1630
- const isStaleUtxo = err?.code === STALE_UTXO_ERROR_CODE || err?.message?.includes("115") || err?.message?.toLowerCase().includes("stale");
1631
- if (isStaleUtxo && attempt < MAX_RETRY_ATTEMPTS) {
1632
- continue;
1633
- }
1634
- const isDustInsufficient = err?.message?.toLowerCase().includes("not enough dust") || err?.message?.toLowerCase().includes("dust generated");
1635
- if (isDustInsufficient && attempt < MAX_RETRY_ATTEMPTS) {
1636
- onDust?.("Waiting for more dust to accumulate...");
1637
- await new Promise((resolve4) => setTimeout(resolve4, DUST_REGISTRATION_RETRY_DELAY_MS));
1638
- continue;
1639
- }
1640
- throw err;
1641
- }
1642
- }
1643
- throw lastError ?? new Error("Transfer failed after retries");
1644
- }
1645
- async function executeTransfer(params) {
1646
- const {
1647
- seedBuffer,
1648
- networkConfig,
1649
- recipientAddress,
1650
- amountNight,
1651
- signal,
1652
- onSync,
1653
- onDust,
1654
- onProving,
1655
- onSubmitting,
1656
- onSyncWarning
1657
- } = params;
1658
- const amount = nightToMicro(amountNight);
1659
- validateRecipientAddress(recipientAddress, networkConfig);
1660
- const unsuppress = suppressSdkTransientErrors(onSyncWarning);
1661
- const bundle = buildFacade(seedBuffer, networkConfig);
1662
- let shutdownComplete = false;
1663
- const cleanup = async () => {
1664
- if (!shutdownComplete) {
1665
- shutdownComplete = true;
1666
- try {
1667
- await stopFacade(bundle);
1668
- } catch {
1669
- }
1670
- }
1671
- };
1672
- const onAbort = () => {
1673
- cleanup();
1674
- };
1675
- signal?.addEventListener("abort", onAbort, { once: true });
1676
- try {
1677
- const syncedState = await startAndSyncFacade(bundle, onSync);
1678
- if (signal?.aborted)
1679
- throw new Error("Operation cancelled");
1680
- const unshieldedBalance = syncedState.unshielded.balances[ledger3.unshieldedToken().raw] ?? 0n;
1681
- if (unshieldedBalance < amount) {
1682
- const haveNight = Number(unshieldedBalance) / TOKEN_MULTIPLIER;
1683
- throw new Error(`Insufficient balance: ${haveNight.toFixed(6)} NIGHT available, ` + `${amountNight} NIGHT requested`);
1684
- }
1685
- if (signal?.aborted)
1686
- throw new Error("Operation cancelled");
1687
- await ensureDust(bundle, onDust);
1688
- if (signal?.aborted)
1689
- throw new Error("Operation cancelled");
1690
- const txHash = await buildAndSubmitTransfer(bundle, recipientAddress, amount, onProving, onSubmitting, onDust);
1691
- return { txHash, amountMicroNight: amount };
1692
- } finally {
1693
- signal?.removeEventListener("abort", onAbort);
1694
- unsuppress();
1695
- await cleanup();
1696
- }
1697
- }
1698
- var NETWORK_ID_MAP3;
1699
- var init_transfer = __esm(() => {
1700
- init_facade();
1701
- NETWORK_ID_MAP3 = {
1702
- PreProd: NetworkId3.NetworkId.PreProd,
1703
- Preview: NetworkId3.NetworkId.Preview,
1704
- Undeployed: NetworkId3.NetworkId.Undeployed
1705
- };
1706
- });
1707
-
1708
- // src/commands/airdrop.ts
1709
- var exports_airdrop = {};
1710
- __export(exports_airdrop, {
1711
- default: () => airdropCommand
1712
- });
1713
- async function airdropCommand(args, signal) {
1714
- const amountStr = args.subcommand;
1715
- if (!amountStr) {
1716
- throw new Error(`Missing amount.
1717
- ` + `Usage: midnight airdrop <amount>
1718
- ` + "Example: midnight airdrop 1000");
1719
- }
1720
- const amountNight = parseAmount(amountStr);
1721
- const walletPath = getFlag(args, "wallet");
1722
- const config = loadWalletConfig(walletPath);
1723
- const { name: networkName, config: networkConfig } = resolveNetwork({
1724
- args,
1725
- walletNetwork: config.network,
1726
- address: config.address
1727
- });
1728
- if (networkName !== "undeployed") {
1729
- throw new Error(`Airdrop is only available on the "undeployed" network (local devnet).
1730
- ` + `Current network: "${networkName}"
1731
- ` + `On preprod/preview, use a faucet or transfer from another wallet.`);
1732
- }
1733
- const recipientAddress = config.address;
1734
- const genesisSeedBuffer = Buffer.from(GENESIS_SEED, "hex");
1735
- process.stderr.write(`
1736
- ` + header("Airdrop") + `
1737
-
1738
- `);
1739
- process.stderr.write(keyValue("Network", networkName) + `
1740
- `);
1741
- process.stderr.write(keyValue("From", dim("genesis (seed 0x01)")) + `
1742
- `);
1743
- process.stderr.write(keyValue("To", formatAddress(recipientAddress, true)) + `
1744
- `);
1745
- process.stderr.write(keyValue("Amount", bold(amountNight + " NIGHT")) + `
1746
- `);
1747
- process.stderr.write(`
1748
- `);
1749
- const spinner = start("Starting genesis wallet...");
1750
- try {
1751
- const result = await executeTransfer({
1752
- seedBuffer: genesisSeedBuffer,
1753
- networkConfig,
1754
- recipientAddress,
1755
- amountNight,
1756
- signal,
1757
- onSync(applied, highest) {
1758
- if (highest > 0) {
1759
- const pct = Math.round(applied / highest * 100);
1760
- spinner.update(`Syncing genesis wallet... ${pct}%`);
1761
- }
1762
- },
1763
- onDust(status) {
1764
- spinner.update(`Dust: ${status}`);
1765
- },
1766
- onProving() {
1767
- spinner.update("Generating ZK proof (this may take a few minutes)...");
1768
- },
1769
- onSubmitting() {
1770
- spinner.update("Submitting transaction...");
1771
- },
1772
- onSyncWarning(_tag, msg) {
1773
- spinner.update(`Syncing genesis wallet... (${msg}, retrying)`);
1774
- }
1775
- });
1776
- spinner.stop("Transaction submitted");
1777
- if (hasFlag(args, "json")) {
1778
- writeJsonResult({
1779
- txHash: result.txHash,
1780
- amount: amountNight,
1781
- recipient: recipientAddress,
1782
- network: networkName
1783
- });
1784
- return;
1785
- }
1786
- process.stdout.write(result.txHash + `
1787
- `);
1788
- process.stderr.write(`
1789
- ` + successMessage(`Airdropped ${amountNight} NIGHT to your wallet`, result.txHash) + `
1790
- `);
1791
- process.stderr.write(`
1792
- ` + divider() + `
1793
- `);
1794
- process.stderr.write(dim(" Verify: midnight balance") + `
1795
- `);
1796
- process.stderr.write(dim(" Register dust: midnight dust register") + `
1797
- `);
1798
- process.stderr.write(dim(" Note: Dust generation takes a few minutes on a fresh wallet.") + `
1799
- `);
1800
- process.stderr.write(dim(" It will happen automatically on your first transfer.") + `
1801
-
1802
- `);
1803
- } catch (err) {
1804
- spinner.stop("Failed");
1805
- if (err instanceof Error && err.message.toLowerCase().includes("dust")) {
1806
- throw new Error(`${err.message}
1807
-
1808
- ` + `On a fresh localnet, the minimum airdrop is ~1 NIGHT.
1809
- ` + `Try: midnight airdrop 1`);
1810
- }
1811
- throw err;
1812
- }
1813
- }
1814
- var init_airdrop = __esm(() => {
1815
- init_wallet_config();
1816
- init_resolve_network();
1817
- init_transfer();
1818
- init_format();
1819
- init_spinner();
1820
- });
1821
-
1822
- // src/commands/transfer.ts
1823
- var exports_transfer = {};
1824
- __export(exports_transfer, {
1825
- default: () => transferCommand
1826
- });
1827
- async function transferCommand(args, signal) {
1828
- const recipientAddress = args.subcommand;
1829
- const amountStr = args.positionals[0];
1830
- if (!recipientAddress) {
1831
- throw new Error(`Missing recipient address.
1832
- ` + `Usage: midnight transfer <to> <amount>
1833
- ` + "Example: midnight transfer mn_addr_undeployed1... 100");
1834
- }
1835
- if (!amountStr) {
1836
- throw new Error(`Missing amount.
1837
- ` + `Usage: midnight transfer <to> <amount>
1838
- ` + "Example: midnight transfer mn_addr_undeployed1... 100");
1839
- }
1840
- const amountNight = parseAmount(amountStr);
1841
- const walletPath = getFlag(args, "wallet");
1842
- const config = loadWalletConfig(walletPath);
1843
- const seedBuffer = Buffer.from(config.seed, "hex");
1844
- const { name: networkName, config: networkConfig } = resolveNetwork({
1845
- args,
1846
- walletNetwork: config.network,
1847
- address: config.address
1848
- });
1849
- process.stderr.write(`
1850
- ` + header("Transfer") + `
1851
-
1852
- `);
1853
- process.stderr.write(keyValue("Network", networkName) + `
1854
- `);
1855
- process.stderr.write(keyValue("From", formatAddress(config.address, true)) + `
1856
- `);
1857
- process.stderr.write(keyValue("To", formatAddress(recipientAddress, true)) + `
1858
- `);
1859
- process.stderr.write(keyValue("Amount", bold(amountNight + " NIGHT")) + `
1860
- `);
1861
- process.stderr.write(`
1862
- `);
1863
- const spinner = start("Starting wallet...");
1864
- try {
1865
- const result = await executeTransfer({
1866
- seedBuffer,
1867
- networkConfig,
1868
- recipientAddress,
1869
- amountNight,
1870
- signal,
1871
- onSync(applied, highest) {
1872
- if (highest > 0) {
1873
- const pct = Math.round(applied / highest * 100);
1874
- spinner.update(`Syncing wallet... ${pct}%`);
1875
- }
1876
- },
1877
- onDust(status) {
1878
- spinner.update(`Dust: ${status}`);
1879
- },
1880
- onProving() {
1881
- spinner.update("Generating ZK proof (this may take a few minutes)...");
1882
- },
1883
- onSubmitting() {
1884
- spinner.update("Submitting transaction...");
1885
- },
1886
- onSyncWarning(_tag, msg) {
1887
- spinner.update(`Syncing wallet... (${msg}, retrying)`);
1888
- }
1889
- });
1890
- spinner.stop("Transaction submitted");
1891
- if (hasFlag(args, "json")) {
1892
- writeJsonResult({
1893
- txHash: result.txHash,
1894
- amount: amountNight,
1895
- recipient: recipientAddress,
1896
- network: networkName
1897
- });
1898
- return;
1899
- }
1900
- process.stdout.write(result.txHash + `
1901
- `);
1902
- process.stderr.write(`
1903
- ` + successMessage(`Transferred ${amountNight} NIGHT`, result.txHash) + `
1904
- `);
1905
- process.stderr.write(`
1906
- ` + divider() + `
1907
- `);
1908
- process.stderr.write(dim(" Verify: midnight balance") + `
1909
-
1910
- `);
1911
- } catch (err) {
1912
- spinner.stop("Failed");
1913
- throw err;
1914
- }
1915
- }
1916
- var init_transfer2 = __esm(() => {
1917
- init_wallet_config();
1918
- init_resolve_network();
1919
- init_transfer();
1920
- init_format();
1921
- init_spinner();
1922
- });
1923
-
1924
- // src/commands/dust.ts
1925
- var exports_dust = {};
1926
- __export(exports_dust, {
1927
- default: () => dustCommand
1928
- });
1929
- import * as ledger4 from "@midnight-ntwrk/ledger-v7";
1930
- import * as rx3 from "rxjs";
1931
- async function dustCommand(args, signal) {
1932
- const subcommand = args.subcommand;
1933
- if (!subcommand || subcommand !== "register" && subcommand !== "status") {
1934
- throw new Error(`Missing or invalid subcommand.
1935
- ` + `Usage:
1936
- ` + ` midnight dust register Register NIGHT UTXOs for dust generation
1937
- ` + " midnight dust status Check dust registration status");
1938
- }
1939
- const walletPath = getFlag(args, "wallet");
1940
- const config = loadWalletConfig(walletPath);
1941
- const seedBuffer = Buffer.from(config.seed, "hex");
1942
- const { name: networkName, config: networkConfig } = resolveNetwork({
1943
- args,
1944
- walletNetwork: config.network,
1945
- address: config.address
1946
- });
1947
- const bundle = buildFacade(seedBuffer, networkConfig);
1948
- const cleanup = async () => {
1949
- try {
1950
- await stopFacade(bundle);
1951
- } catch {
1952
- }
1953
- };
1954
- const onAbort = () => {
1955
- cleanup();
1956
- };
1957
- signal?.addEventListener("abort", onAbort, { once: true });
1958
- const warningRef = {};
1959
- const unsuppress = suppressSdkTransientErrors((tag, msg) => {
1960
- warningRef.current?.(tag, msg);
1961
- });
1962
- const isJson = hasFlag(args, "json");
1963
- try {
1964
- if (subcommand === "register") {
1965
- await dustRegister(bundle, networkName, isJson, signal, warningRef);
1966
- } else {
1967
- await dustStatus(bundle, networkName, isJson, signal, warningRef);
1968
- }
1969
- } finally {
1970
- signal?.removeEventListener("abort", onAbort);
1971
- unsuppress();
1972
- await cleanup();
1973
- }
1974
- }
1975
- async function dustRegister(bundle, networkName, jsonMode, signal, warningRef) {
1976
- process.stderr.write(`
1977
- ` + header("Dust Register") + `
1978
-
1979
- `);
1980
- process.stderr.write(keyValue("Network", networkName) + `
1981
-
1982
- `);
1983
- const spinner = start("Syncing wallet...");
1984
- if (warningRef) {
1985
- warningRef.current = (_tag, msg) => spinner.update(`Syncing wallet... (${msg}, retrying)`);
1986
- }
1987
- try {
1988
- await startAndSyncFacade(bundle, (applied, highest) => {
1989
- if (highest > 0) {
1990
- const pct = Math.round(applied / highest * 100);
1991
- spinner.update(`Syncing wallet... ${pct}%`);
1992
- }
1993
- });
1994
- if (signal?.aborted)
1995
- throw new Error("Operation cancelled");
1996
- spinner.update("Checking dust status...");
1997
- const state = await rx3.firstValueFrom(bundle.facade.state().pipe(rx3.filter((s) => s.isSynced)));
1998
- if (state.dust.availableCoins.length > 0) {
1999
- const dustBal2 = state.dust.walletBalance(new Date);
2000
- spinner.stop("Dust already available");
2001
- if (jsonMode) {
2002
- writeJsonResult({ subcommand: "register", dustBalance: toDust(dustBal2) });
2003
- return;
2004
- }
2005
- process.stdout.write(dustBal2.toString() + `
2006
- `);
2007
- process.stderr.write(`
2008
- ` + successMessage(`Dust tokens already available: ${formatDust(dustBal2)}`) + `
2009
-
2010
- `);
2011
- return;
2012
- }
2013
- const nightUtxos = state.unshielded.availableCoins.filter((coin) => coin.meta?.registeredForDustGeneration !== true);
2014
- let txHash;
2015
- if (nightUtxos.length === 0) {
2016
- spinner.update("All UTXOs already registered, waiting for dust generation...");
2017
- } else {
2018
- spinner.update(`Registering ${nightUtxos.length} UTXO(s) for dust generation...`);
2019
- const dustUtxos = nightUtxos.map((coin) => ({
2020
- ...coin.utxo,
2021
- ctime: new Date(coin.meta.ctime)
2022
- }));
2023
- txHash = await registerNightUtxos(bundle, dustUtxos, state.dust.dustAddress, (status) => {
2024
- spinner.update(status);
2025
- });
2026
- spinner.update(`Registration submitted (${txHash.slice(0, 12)}...), waiting for dust...`);
2027
- }
2028
- if (signal?.aborted)
2029
- throw new Error("Operation cancelled");
2030
- const dustState = await rx3.firstValueFrom(bundle.facade.state().pipe(rx3.throttleTime(5000), rx3.filter((s) => s.isSynced), rx3.filter((s) => s.dust.walletBalance(new Date) > 0n), rx3.timeout(DUST_TIMEOUT_MS)));
2031
- const dustBal = dustState.dust.walletBalance(new Date);
2032
- spinner.stop("Dust registration complete");
2033
- if (jsonMode) {
2034
- const result = { subcommand: "register", dustBalance: toDust(dustBal) };
2035
- if (txHash)
2036
- result.txHash = txHash;
2037
- writeJsonResult(result);
2038
- return;
2039
- }
2040
- process.stdout.write(dustBal.toString() + `
2041
- `);
2042
- process.stderr.write(`
2043
- ` + successMessage(`Dust tokens available: ${formatDust(dustBal)}`) + `
2044
-
2045
- `);
2046
- } catch (err) {
2047
- spinner.stop("Failed");
2048
- throw err;
2049
- }
2050
- }
2051
- async function dustStatus(bundle, networkName, jsonMode, signal, warningRef) {
2052
- process.stderr.write(`
2053
- ` + header("Dust Status") + `
2054
-
2055
- `);
2056
- process.stderr.write(keyValue("Network", networkName) + `
2057
-
2058
- `);
2059
- const spinner = start("Syncing wallet...");
2060
- if (warningRef) {
2061
- warningRef.current = (_tag, msg) => spinner.update(`Syncing wallet... (${msg}, retrying)`);
2062
- }
2063
- try {
2064
- await startAndSyncFacade(bundle, (applied, highest) => {
2065
- if (highest > 0) {
2066
- const pct = Math.round(applied / highest * 100);
2067
- spinner.update(`Syncing wallet... ${pct}%`);
2068
- }
2069
- });
2070
- if (signal?.aborted)
2071
- throw new Error("Operation cancelled");
2072
- spinner.update("Checking dust status...");
2073
- const state = await rx3.firstValueFrom(bundle.facade.state().pipe(rx3.filter((s) => s.isSynced)));
2074
- const dustBalance = state.dust.walletBalance(new Date);
2075
- const hasAvailableDust = state.dust.availableCoins.length > 0;
2076
- const allUtxos = state.unshielded.availableCoins;
2077
- const unregisteredUtxos = allUtxos.filter((coin) => coin.meta?.registeredForDustGeneration !== true);
2078
- const registeredCount = allUtxos.length - unregisteredUtxos.length;
2079
- const unshieldedBalance = state.unshielded.balances[ledger4.unshieldedToken().raw] ?? 0n;
2080
- spinner.stop("Done");
2081
- if (jsonMode) {
2082
- writeJsonResult({
2083
- subcommand: "status",
2084
- dustBalance: toDust(dustBalance),
2085
- registered: registeredCount,
2086
- unregistered: unregisteredUtxos.length,
2087
- nightBalance: toNight(unshieldedBalance),
2088
- dustAvailable: hasAvailableDust
2089
- });
2090
- return;
2091
- }
2092
- process.stdout.write(`dust=${dustBalance}
2093
- `);
2094
- process.stdout.write(`registered=${registeredCount}
2095
- `);
2096
- process.stdout.write(`unregistered=${unregisteredUtxos.length}
2097
- `);
2098
- process.stderr.write(keyValue("NIGHT Balance", bold(formatNight(unshieldedBalance))) + `
2099
- `);
2100
- process.stderr.write(keyValue("Dust Balance", bold(formatDust(dustBalance))) + `
2101
- `);
2102
- process.stderr.write(keyValue("Dust Available", hasAvailableDust ? "yes" : "no") + `
2103
- `);
2104
- process.stderr.write(keyValue("Registered", registeredCount.toString() + " UTXO(s)") + `
2105
- `);
2106
- process.stderr.write(keyValue("Unregistered", unregisteredUtxos.length.toString() + " UTXO(s)") + `
2107
- `);
2108
- process.stderr.write(`
2109
- ` + divider() + `
2110
-
2111
- `);
2112
- } catch (err) {
2113
- spinner.stop("Failed");
2114
- throw err;
2115
- }
2116
- }
2117
- var init_dust = __esm(() => {
2118
- init_wallet_config();
2119
- init_resolve_network();
2120
- init_facade();
2121
- init_transfer();
2122
- init_format();
2123
- init_spinner();
2124
- });
2125
-
2126
- // src/commands/config.ts
2127
- var exports_config = {};
2128
- __export(exports_config, {
2129
- default: () => configCommand
2130
- });
2131
- async function configCommand(args) {
2132
- const action = args.subcommand;
2133
- if (!action || action !== "get" && action !== "set") {
2134
- throw new Error(`Usage: midnight config <get|set> <key> [value]
2135
- ` + `Valid keys: ${getValidConfigKeys().join(", ")}`);
2136
- }
2137
- const key = args.positionals[0];
2138
- if (!key) {
2139
- throw new Error(`Missing config key.
2140
- ` + `Valid keys: ${getValidConfigKeys().join(", ")}`);
2141
- }
2142
- if (action === "get") {
2143
- const value = getConfigValue(key);
2144
- if (hasFlag(args, "json")) {
2145
- writeJsonResult({ action: "get", key, value });
2146
- return;
2147
- }
2148
- process.stdout.write(value + `
2149
- `);
2150
- } else {
2151
- const value = args.positionals[1];
2152
- if (value === undefined) {
2153
- throw new Error(`Missing value for config set.
2154
- Usage: midnight config set ${key} <value>`);
2155
- }
2156
- setConfigValue(key, value);
2157
- if (hasFlag(args, "json")) {
2158
- writeJsonResult({ action: "set", key, value });
2159
- return;
2160
- }
2161
- process.stderr.write(green("✓") + ` ${key} = ${value}
2162
- `);
2163
- }
2164
- }
2165
- var init_config = __esm(() => {
2166
- init_cli_config();
2167
- });
2168
-
2169
- // src/lib/localnet.ts
2170
- import { execSync as execSync2 } from "child_process";
2171
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
2172
- import { homedir as homedir5 } from "os";
2173
- import { join as join5 } from "path";
2174
- function checkDockerAvailable() {
2175
- try {
2176
- const output = execSync2("docker compose version", { ...EXEC_OPTIONS, timeout: 1e4 });
2177
- return output.trim();
2178
- } catch {
2179
- try {
2180
- execSync2("docker --version", { ...EXEC_OPTIONS, timeout: 5000 });
2181
- throw new Error(`Docker Compose v2 is required.
2182
- ` + "Install it from https://docs.docker.com/compose/install/");
2183
- } catch (innerErr) {
2184
- if (innerErr instanceof Error && innerErr.message.includes("Docker Compose v2")) {
2185
- throw innerErr;
2186
- }
2187
- throw new Error(`Docker is required but was not found.
2188
- ` + "Install Docker from https://docs.docker.com/get-docker/");
2189
- }
2190
- }
2191
- }
2192
- function ensureComposeFile() {
2193
- const versionMatches = existsSync4(VERSION_PATH) && existsSync4(COMPOSE_PATH) && readFileSync3(VERSION_PATH, "utf-8").trim() === COMPOSE_VERSION;
2194
- if (versionMatches)
2195
- return false;
2196
- mkdirSync3(LOCALNET_DIR, { recursive: true, mode: DIR_MODE });
2197
- writeFileSync3(COMPOSE_PATH, COMPOSE_YAML, "utf-8");
2198
- writeFileSync3(VERSION_PATH, COMPOSE_VERSION, "utf-8");
2199
- return true;
2200
- }
2201
- function dockerCompose(args) {
2202
- return execSync2(`docker compose -f "${COMPOSE_PATH}" ${args}`, EXEC_OPTIONS);
2203
- }
2204
- function getServiceStatus() {
2205
- try {
2206
- const output = dockerCompose("ps --format json");
2207
- if (!output.trim())
2208
- return [];
2209
- const lines = output.trim().split(`
2210
- `);
2211
- const services = [];
2212
- for (const line of lines) {
2213
- if (!line.trim())
2214
- continue;
2215
- try {
2216
- const obj = JSON.parse(line);
2217
- const name = obj.Service ?? "unknown";
2218
- services.push({
2219
- name,
2220
- state: obj.State ?? "unknown",
2221
- health: obj.Health ?? "",
2222
- port: PORT_MAP[name] ?? ""
2223
- });
2224
- } catch {
2225
- }
2226
- }
2227
- return services;
2228
- } catch {
2229
- return [];
2230
- }
2231
- }
2232
- function waitForHealthy(timeoutMs = 120000, intervalMs = 3000) {
2233
- const deadline = Date.now() + timeoutMs;
2234
- while (Date.now() < deadline) {
2235
- const services = getServiceStatus();
2236
- const allRunning = services.length === 3 && services.every((s) => s.state === "running");
2237
- if (allRunning) {
2238
- const healthyOrNoCheck = services.every((s) => s.health === "healthy" || s.health === "");
2239
- if (healthyOrNoCheck)
2240
- return true;
2241
- }
2242
- execSync2(`sleep ${intervalMs / 1000}`, { timeout: intervalMs + 1000 });
2243
- }
2244
- return false;
2245
- }
2246
- function getComposePath() {
2247
- return COMPOSE_PATH;
2248
- }
2249
- function removeConflictingContainers() {
2250
- const removed = [];
2251
- for (const name of CONTAINER_NAMES) {
2252
- try {
2253
- execSync2(`docker rm -f "${name}"`, { ...EXEC_OPTIONS, timeout: 1e4 });
2254
- removed.push(name);
2255
- } catch {
2256
- }
2257
- }
2258
- return removed;
2259
- }
2260
- var COMPOSE_VERSION = "1.4.0", LOCALNET_DIR, COMPOSE_PATH, VERSION_PATH, COMPOSE_YAML = `services:
62
+ `;var k3=()=>{};function v($){if(!i())return process.stderr.write(`⠋ ${$}`),{update(z){process.stderr.write(`\r⠋ ${z}`)},stop(z){let Y=z??$;process.stderr.write(`\r✓ ${Y}
63
+ `)}};let Z=0,Q=$,X=()=>{let z=t(b3[Z]);process.stderr.write(`\r${z} ${Q}\x1B[K`),Z=(Z+1)%b3.length};X();let q=setInterval(X,g2);return{update(z){Q=z},stop(z){clearInterval(q);let Y=z??Q;process.stderr.write(`\r\x1B[32m✓\x1B[0m ${Y}\x1B[K
64
+ `)}}}var b3,g2=80;var B0=O(()=>{b3=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]});var W1={};S(W1,{default:()=>w3});async function w3($){let Z,Q;if($.subcommand)Z=$.subcommand;else{let G=A($,"wallet"),U=d(G);Z=U.address,Q=U.network}if(!Z)throw new Error("No address provided and no wallet file found.");let{name:X,config:q}=r({args:$,walletNetwork:Q,address:Z}),Y=A($,"indexer-ws")??q.indexerWS,K=v(`Checking balance on ${X}...`);try{let G=await v3(Z,Y,(U,V)=>{if(V>0){let J=Math.round(U/V*100);K.update(`Syncing transactions... ${J}%`)}});if(K.stop(`Synced ${G.txCount} transactions`),P($,"json")){let U={};for(let[V,J]of G.balances){let W=T0(V)?"NIGHT":V;U[W]=T0(V)?O0(J):J.toString()}L({address:Z,network:X,balances:U,utxoCount:G.utxoCount,txCount:G.txCount});return}if(G.balances.size===0)process.stdout.write(`0
65
+ `);else for(let[U,V]of G.balances)if(T0(U))process.stdout.write(`NIGHT=${V}
66
+ `);else process.stdout.write(`${U}=${V}
67
+ `);if(process.stderr.write(`
68
+ `+I("Balance")+`
69
+
70
+ `),process.stderr.write(H("Address",E(Z))+`
71
+ `),process.stderr.write(H("Network",X)+`
72
+ `),process.stderr.write(H("UTXOs",G.utxoCount.toString())+`
73
+ `),process.stderr.write(H("Transactions",G.txCount.toString())+`
74
+ `),process.stderr.write(`
75
+ `),G.balances.size===0)process.stderr.write(` ${j("No balance found")}
76
+ `);else for(let[U,V]of G.balances)if(T0(U))process.stderr.write(H("NIGHT",y(v0(V)))+`
77
+ `);else{let J=U.slice(0,8)+"…"+U.slice(-8);process.stderr.write(H(`Token ${J}`,y(V.toString()))+`
78
+ `)}process.stderr.write(`
79
+ `+D()+`
80
+
81
+ `)}catch(G){throw K.stop("Failed"),G}}var H1=O(()=>{Y0();s();k3();N();B0()});var j1={};S(j1,{default:()=>S3});async function S3($){let Z=n1($,"seed","hex").replace(/^0x/,"");if(Z.length!==64||!/^[0-9a-fA-F]+$/.test(Z))throw new Error("Seed must be a 64-character hex string (32 bytes)");let Q=A($,"index"),X=Q!==void 0?parseInt(Q,10):0;if(isNaN(X)||X<0||!Number.isInteger(Number(Q??"0")))throw new Error("Key index must be a non-negative integer");let q=Buffer.from(Z,"hex"),z=z0({args:$}),Y=U0(q,z,X),K=`m/44'/2400'/0'/NightExternal/${X}`;if(P($,"json")){L({address:Y,network:z,index:X,path:K});return}process.stdout.write(Y+`
82
+ `),process.stderr.write(`
83
+ `),process.stderr.write(H("Network",z)+`
84
+ `),process.stderr.write(H("Index",X.toString())+`
85
+ `),process.stderr.write(H("Address",E(Y))+`
86
+ `),process.stderr.write(H("Path",j(K))+`
87
+ `),process.stderr.write(D()+`
88
+
89
+ `)}var F1=O(()=>{S0();s();N()});var P1={};S(P1,{default:()=>C3});async function C3($){let Z=z0({args:$}),Q=Buffer.from(D0,"hex"),X=U0(Q,Z);if(P($,"json")){L({address:X,network:Z});return}process.stdout.write(X+`
90
+ `),process.stderr.write(`
91
+ `),process.stderr.write(H("Network",Z)+`
92
+ `),process.stderr.write(H("Address",E(X))+`
93
+ `),process.stderr.write(H("Seed",j("0x01 (genesis)"))+`
94
+ `),process.stderr.write(D()+`
95
+
96
+ `)}var O1=O(()=>{S0();s();N()});var L1={};S(L1,{default:()=>h3});import*as f3 from"@midnight-ntwrk/ledger-v7";function M0($,Z,Q){let X={readTime:0n,computeTime:0n,blockUsage:0n,bytesWritten:0n,bytesChurned:0n};X[Z]=Q;let z=$.normalizeFullness(X)[Z];return Math.round(Number(Q)/z)}function d2($){return{readTime:M0($,"readTime",1000000000n),computeTime:M0($,"computeTime",1000000000n),blockUsage:M0($,"blockUsage",10000n),bytesWritten:M0($,"bytesWritten",10000n),bytesChurned:M0($,"bytesChurned",1000000n)}}async function h3($){let Z=f3.LedgerParameters.initialParameters(),Q=d2(Z);if(P($,"json")){L(Q);return}for(let[X,q]of Object.entries(Q))process.stdout.write(`${X}=${q}
97
+ `);process.stderr.write(`
98
+ `+I("Block Limits")+`
99
+
100
+ `),process.stderr.write(j(" Derived from LedgerParameters.initialParameters()")+`
101
+
102
+ `);for(let[X,q]of Object.entries(Q)){let z=l2[X]??"";process.stderr.write(H(X,`${y(q.toLocaleString())} ${j(z)}`)+`
103
+ `)}process.stderr.write(`
104
+ `+D()+`
105
+ `),process.stderr.write(j(" bytesWritten is typically the tightest constraint")+`
106
+ `),process.stderr.write(j(" for large contract deployments.")+`
107
+
108
+ `)}var l2;var y1=O(()=>{N();l2={readTime:"picoseconds",computeTime:"picoseconds",blockUsage:"bytes",bytesWritten:"bytes",bytesChurned:"bytes"}});import{HDWallet as i2,Roles as T1}from"@midnight-ntwrk/wallet-sdk-hd";function M1($,Z){let Q=i2.fromSeed($);if(Q.type!=="seedOk")throw new Error("Invalid seed for HD wallet");let X=Q.hdWallet.selectAccount(0).selectRole(Z).deriveKeyAt(0);if(X.type==="keyOutOfBounds")throw new Error("Key derivation out of bounds");return X.key}function p3($){return M1($,T1.Zswap)}function u3($){return M1($,T1.NightExternal)}function c3($){return M1($,T1.Dust)}var m3=()=>{};import{ShieldedWallet as o2}from"@midnight-ntwrk/wallet-sdk-shielded";import{UnshieldedWallet as n2,createKeystore as a2,PublicKey as t2,InMemoryTransactionHistoryStorage as r2}from"@midnight-ntwrk/wallet-sdk-unshielded-wallet";import{DustWallet as s2}from"@midnight-ntwrk/wallet-sdk-dust-wallet";import{WalletFacade as e2}from"@midnight-ntwrk/wallet-sdk-facade";import*as V0 from"@midnight-ntwrk/ledger-v7";import{NetworkId as I1}from"@midnight-ntwrk/wallet-sdk-abstractions";import*as p from"rxjs";function c0($,Z){let Q=$$[Z.networkId];if(Q===void 0)throw new Error(`Unknown networkId: ${Z.networkId}`);let X=p3($),q=u3($),z=c3($),Y=V0.ZswapSecretKeys.fromSeed(X),K=V0.DustSecretKey.fromSeed(z),G=a2(q,Q),U={networkId:Q,indexerClientConnection:{indexerHttpUrl:Z.indexer,indexerWsUrl:Z.indexerWS},provingServerUrl:new URL(Z.proofServer),relayURL:new URL(Z.node)},V={networkId:Q,indexerClientConnection:{indexerHttpUrl:Z.indexer,indexerWsUrl:Z.indexerWS},txHistoryStorage:new r2},J={networkId:Q,costParameters:{additionalFeeOverhead:r1,feeBlocksMargin:s1},indexerClientConnection:{indexerHttpUrl:Z.indexer,indexerWsUrl:Z.indexerWS},provingServerUrl:new URL(Z.proofServer),relayURL:new URL(Z.node)},W=o2(U).startWithSecretKeys(Y),B=n2(V).startWithPublicKey(t2.fromKeyStore(G)),F=s2(J).startWithSecretKey(K,V0.LedgerParameters.initialParameters().dust);return{facade:new e2(W,B,F),keystore:G,zswapSecretKeys:Y,dustSecretKey:K}}async function I0($,Z){let{facade:Q,zswapSecretKeys:X,dustSecretKey:q}=$;return await Q.start(X,q),p.firstValueFrom(Q.state().pipe(p.tap((z)=>{if(Z){let Y=z.unshielded.progress;if(Y)Z(Number(Y.appliedId),Number(Y.highestTransactionId))}}),p.filter((z)=>z.isSynced),p.timeout(e1)))}async function g3($){return p.firstValueFrom($.facade.state().pipe(p.filter((Z)=>Z.isSynced),p.timeout($3)))}async function m0($){await $.facade.stop()}function g0($){let Z=(X)=>{let q=X?._tag;if(typeof q==="string"&&q.startsWith("Wallet.")){let z=X?.message??"transient error";$?.(q,z);return}Q("Unhandled rejection:",X),process.exit(1)},Q=console.error;return console.error=(...X)=>{let q=X[0];if(typeof q==="object"&&q?._tag?.startsWith("Wallet.")){$?.(q._tag,q?.message??"transient error");return}if(typeof q==="string"&&q.startsWith("Wallet.")){$?.("Wallet.Sync","transient error");return}Q(...X)},process.on("unhandledRejection",Z),()=>{process.removeListener("unhandledRejection",Z),console.error=Q}}var $$;var _1=O(()=>{m3();$$={PreProd:I1.NetworkId.PreProd,Preview:I1.NetworkId.Preview,Undeployed:I1.NetworkId.Undeployed}});import*as D1 from"@midnight-ntwrk/ledger-v7";import{MidnightBech32m as Z$,UnshieldedAddress as Q$}from"@midnight-ntwrk/wallet-sdk-address-format";import{NetworkId as A1}from"@midnight-ntwrk/wallet-sdk-abstractions";import*as u from"rxjs";function q$($){if($<=0)throw new Error("Amount must be greater than 0");if(!Number.isFinite($))throw new Error("Amount must be a finite number");let Z=$.toFixed(6),[Q,X]=Z.split("."),q=Q+(X??"").padEnd(6,"0"),z=BigInt(q);if(z<=0n)throw new Error("Amount too small — minimum is 0.000001 NIGHT");return z}function d0($){let Z=Number($);if(Number.isNaN(Z)||!Number.isFinite(Z))throw new Error(`Invalid amount: "${$}" — must be a positive number`);if(Z<=0)throw new Error(`Invalid amount: "${$}" — must be greater than 0`);return Z}function z$($,Z){let Q=X$[Z.networkId];if(Q===void 0)throw new Error(`Unknown networkId: ${Z.networkId}`);try{Z$.parse($).decode(Q$,Q)}catch(X){throw new Error(`Invalid recipient address: ${X.message}
109
+ Expected a bech32m address for network "${Z.networkId}"`)}}function d3($){let Z=$;while(Z){let Q=String(Z?.message??"").toLowerCase();if(Q.includes("submission error"))return!0;if(Q.includes("transaction")&&Q.includes("invalid"))return!0;if(Q.includes("138"))return!0;let X=Z?._tag;if(X==="TransactionInvalidError"||X==="SubmissionError")return!0;Z=Z.cause}return!1}function Y$($){let Z=Math.round($/1000);if(Z<60)return`${Z}s`;let Q=Math.floor(Z/60),X=Z%60;return`${Q}m ${X}s`}async function J$($,Z,Q){let X=new Date(Date.now()+$1*60*1000);await $.facade.dust.waitForSyncedState();let q=await $.facade.dust.createDustGenerationTransaction(new Date,X,Z,$.keystore.getPublicKey(),Q),z=q.intents?.get(1);if(!z)throw new Error("Dust generation intent not found on transaction");let Y=$.keystore.signData(z.signatureData(1)),K=await $.facade.dust.addDustGenerationSignature(q,Y),G=await $.facade.finalizeTransaction(K);return await $.facade.submitTransaction(G)}async function R1($,Z,Q,X){let q=Date.now(),z=q+Q3,Y,K=console.warn,G=console.error,U=(W)=>W.some((B)=>String(B).includes("RPC-CORE")),V=()=>{console.warn=(...W)=>{if(U(W))return;K(...W)},console.error=(...W)=>{if(U(W))return;G(...W)}},J=()=>{console.warn=K,console.error=G};V();try{while(Date.now()<z)try{return await J$($,Z,Q)}catch(W){if(Y=W,d3(W)&&Date.now()+E0<z){let B=Y$(Date.now()-q);X?.(`Waiting for dust generation capacity (${B} elapsed, ~5 min on fresh wallets)...`),await new Promise((F)=>setTimeout(F,E0));continue}throw W}throw Y??new Error("Dust registration timed out")}finally{J()}}async function K$($,Z){let Q=await u.firstValueFrom($.facade.state().pipe(u.filter((q)=>q.isSynced))),X=Q.unshielded.availableCoins.filter((q)=>q.meta?.registeredForDustGeneration!==!0);if(X.length>0){Z?.(`Registering ${X.length} UTXO(s) for dust generation...`);let q=X.map((z)=>({...z.utxo,ctime:new Date(z.meta.ctime)}));await R1($,q,Q.dust.dustAddress,Z)}else if(Q.dust.availableCoins.length>0){Z?.("Dust available");return}else Z?.("UTXOs already registered, waiting for dust generation...");Z?.("Waiting for dust tokens..."),await u.firstValueFrom($.facade.state().pipe(u.throttleTime(5000),u.filter((q)=>q.isSynced),u.filter((q)=>q.dust.walletBalance(new Date)>0n),u.timeout(R0))),Z?.("Dust available")}async function G$($,Z,Q,X,q,z){let Y;for(let K=1;K<=x0;K++)try{if(K>1)await g3($);let G=new Date(Date.now()+$1*60*1000),U=await $.facade.transferTransaction([{type:"unshielded",outputs:[{amount:Q,receiverAddress:Z,type:D1.unshieldedToken().raw}]}],{shieldedSecretKeys:$.zswapSecretKeys,dustSecretKey:$.dustSecretKey},{ttl:G,payFees:!0}),V=await $.facade.signRecipe(U,(B)=>$.keystore.signData(B));X?.();let J=await Promise.race([$.facade.finalizeRecipe(V),new Promise((B,F)=>{setTimeout(()=>F(new Error("ZK proof generation timed out")),Z3)})]);return q?.(),await $.facade.submitTransaction(J)}catch(G){if(Y=G,(G?.code===X3||G?.message?.includes("115")||G?.message?.toLowerCase().includes("stale"))&&K<x0)continue;let V=G?.message?.toLowerCase().includes("not enough dust")||G?.message?.toLowerCase().includes("dust generated"),J=d3(G);if((V||J)&&K<x0){z?.("Waiting for more dust capacity to accumulate..."),await new Promise((W)=>setTimeout(W,E0));continue}throw G}throw Y??new Error("Transfer failed after retries")}async function l0($){let{seedBuffer:Z,networkConfig:Q,recipientAddress:X,amountNight:q,signal:z,onSync:Y,onDust:K,onProving:G,onSubmitting:U,onSyncWarning:V}=$,J=q$(q);z$(X,Q);let W=g0(V),B=console.warn,F=console.error,M=(b)=>b.some(($0)=>String($0).includes("RPC-CORE"));console.warn=(...b)=>{if(!M(b))B(...b)},console.error=(...b)=>{if(!M(b))F(...b)};let _=()=>{console.warn=B,console.error=F},T=c0(Z,Q),k=!1,C=async()=>{if(!k){k=!0;try{await m0(T)}catch{}}},c=()=>{C()};z?.addEventListener("abort",c,{once:!0});try{let b=await I0(T,Y);if(z?.aborted)throw new Error("Operation cancelled");let $0=b.unshielded.balances[D1.unshieldedToken().raw]??0n;if($0<J){let O2=Number($0)/t1;throw new Error(`Insufficient balance: ${O2.toFixed(6)} NIGHT available, ${q} NIGHT requested`)}if(z?.aborted)throw new Error("Operation cancelled");if(await K$(T,K),z?.aborted)throw new Error("Operation cancelled");return{txHash:await G$(T,X,J,G,U,K),amountMicroNight:J}}finally{z?.removeEventListener("abort",c),_(),W(),await C()}}var X$;var i0=O(()=>{_1();X$={PreProd:A1.NetworkId.PreProd,Preview:A1.NetworkId.Preview,Undeployed:A1.NetworkId.Undeployed}});var x1={};S(x1,{default:()=>l3});async function l3($,Z){let Q=$.subcommand;if(!Q)throw new Error(`Missing amount.
110
+ Usage: midnight airdrop <amount>
111
+ Example: midnight airdrop 1000`);let X=d0(Q),q=A($,"wallet"),z=d(q),{name:Y,config:K}=r({args:$,walletNetwork:z.network,address:z.address});if(Y!=="undeployed")throw new Error(`Airdrop is only available on the "undeployed" network (local devnet).
112
+ Current network: "${Y}"
113
+ On preprod/preview, use a faucet or transfer from another wallet.`);let G=z.address,U=Buffer.from(D0,"hex");process.stderr.write(`
114
+ `+I("Airdrop")+`
115
+
116
+ `),process.stderr.write(H("Network",Y)+`
117
+ `),process.stderr.write(H("From",j("genesis (seed 0x01)"))+`
118
+ `),process.stderr.write(H("To",E(G,!0))+`
119
+ `),process.stderr.write(H("Amount",y(X+" NIGHT"))+`
120
+ `),process.stderr.write(`
121
+ `);let V=v("Starting genesis wallet...");try{let J=await l0({seedBuffer:U,networkConfig:K,recipientAddress:G,amountNight:X,signal:Z,onSync(W,B){if(B>0){let F=Math.round(W/B*100);V.update(`Syncing genesis wallet... ${F}%`)}},onDust(W){V.update(`Dust: ${W}`)},onProving(){V.update("Generating ZK proof (this may take a few minutes)...")},onSubmitting(){V.update("Submitting transaction...")},onSyncWarning(W,B){V.update(`Syncing genesis wallet... (${B}, retrying)`)}});if(V.stop("Transaction submitted"),P($,"json")){L({txHash:J.txHash,amount:X,recipient:G,network:Y});return}process.stdout.write(J.txHash+`
122
+ `),process.stderr.write(`
123
+ `+X0(`Airdropped ${X} NIGHT to your wallet`,J.txHash)+`
124
+ `),process.stderr.write(`
125
+ `+D()+`
126
+ `),process.stderr.write(j(" Verify: midnight balance")+`
127
+ `),process.stderr.write(j(" Register dust: midnight dust register")+`
128
+ `),process.stderr.write(j(" Note: Dust generation takes a few minutes on a fresh wallet.")+`
129
+ `),process.stderr.write(j(" It will happen automatically on your first transfer.")+`
130
+
131
+ `)}catch(J){if(V.stop("Failed"),J instanceof Error&&J.message.toLowerCase().includes("dust"))throw new Error(`${J.message}
132
+
133
+ On a fresh localnet, the minimum airdrop is ~1 NIGHT.
134
+ Try: midnight airdrop 1`);throw J}}var E1=O(()=>{Y0();s();i0();N();B0()});var N1={};S(N1,{default:()=>i3});async function i3($,Z){let Q=$.subcommand,X=$.positionals[0];if(!Q)throw new Error(`Missing recipient address.
135
+ Usage: midnight transfer <to> <amount>
136
+ Example: midnight transfer mn_addr_undeployed1... 100`);if(!X)throw new Error(`Missing amount.
137
+ Usage: midnight transfer <to> <amount>
138
+ Example: midnight transfer mn_addr_undeployed1... 100`);let q=d0(X),z=A($,"wallet"),Y=d(z),K=Buffer.from(Y.seed,"hex"),{name:G,config:U}=r({args:$,walletNetwork:Y.network,address:Y.address});process.stderr.write(`
139
+ `+I("Transfer")+`
140
+
141
+ `),process.stderr.write(H("Network",G)+`
142
+ `),process.stderr.write(H("From",E(Y.address,!0))+`
143
+ `),process.stderr.write(H("To",E(Q,!0))+`
144
+ `),process.stderr.write(H("Amount",y(q+" NIGHT"))+`
145
+ `),process.stderr.write(`
146
+ `);let V=v("Starting wallet...");try{let J=await l0({seedBuffer:K,networkConfig:U,recipientAddress:Q,amountNight:q,signal:Z,onSync(W,B){if(B>0){let F=Math.round(W/B*100);V.update(`Syncing wallet... ${F}%`)}},onDust(W){V.update(`Dust: ${W}`)},onProving(){V.update("Generating ZK proof (this may take a few minutes)...")},onSubmitting(){V.update("Submitting transaction...")},onSyncWarning(W,B){V.update(`Syncing wallet... (${B}, retrying)`)}});if(V.stop("Transaction submitted"),P($,"json")){L({txHash:J.txHash,amount:q,recipient:Q,network:G});return}process.stdout.write(J.txHash+`
147
+ `),process.stderr.write(`
148
+ `+X0(`Transferred ${q} NIGHT`,J.txHash)+`
149
+ `),process.stderr.write(`
150
+ `+D()+`
151
+ `),process.stderr.write(j(" Verify: midnight balance")+`
152
+
153
+ `)}catch(J){throw V.stop("Failed"),J}}var v1=O(()=>{Y0();s();i0();N();B0()});var k1={};S(k1,{default:()=>n3});import*as o3 from"@midnight-ntwrk/ledger-v7";import*as w from"rxjs";async function n3($,Z){let Q=$.subcommand;if(!Q||Q!=="register"&&Q!=="status")throw new Error(`Missing or invalid subcommand.
154
+ Usage:
155
+ midnight dust register Register NIGHT UTXOs for dust generation
156
+ midnight dust status Check dust registration status`);let X=A($,"wallet"),q=d(X),z=Buffer.from(q.seed,"hex"),{name:Y,config:K}=r({args:$,walletNetwork:q.network,address:q.address}),G=c0(z,K),U=async()=>{try{await m0(G)}catch{}},V=()=>{U()};Z?.addEventListener("abort",V,{once:!0});let J={},W=g0((F,M)=>{J.current?.(F,M)}),B=P($,"json");try{if(Q==="register")await U$(G,Y,B,Z,J);else await B$(G,Y,B,Z,J)}finally{Z?.removeEventListener("abort",V),W(),await U()}}async function U$($,Z,Q,X,q){process.stderr.write(`
157
+ `+I("Dust Register")+`
158
+
159
+ `),process.stderr.write(H("Network",Z)+`
160
+
161
+ `);let z=v("Syncing wallet...");if(q)q.current=(Y,K)=>z.update(`Syncing wallet... (${K}, retrying)`);try{if(await I0($,(J,W)=>{if(W>0){let B=Math.round(J/W*100);z.update(`Syncing wallet... ${B}%`)}}),X?.aborted)throw new Error("Operation cancelled");z.update("Checking dust status...");let Y=await w.firstValueFrom($.facade.state().pipe(w.filter((J)=>J.isSynced)));if(Y.dust.availableCoins.length>0){let J=Y.dust.walletBalance(new Date);if(z.stop("Dust already available"),Q){L({subcommand:"register",dustBalance:L0(J)});return}process.stdout.write(J.toString()+`
162
+ `),process.stderr.write(`
163
+ `+X0(`Dust tokens already available: ${k0(J)}`)+`
164
+
165
+ `);return}let K=Y.unshielded.availableCoins.filter((J)=>J.meta?.registeredForDustGeneration!==!0),G;if(K.length===0)z.update("All UTXOs already registered, waiting for dust generation...");else{z.update(`Registering ${K.length} UTXO(s) for dust generation...`);let J=K.map((W)=>({...W.utxo,ctime:new Date(W.meta.ctime)}));G=await R1($,J,Y.dust.dustAddress,(W)=>{z.update(W)}),z.update(`Registration submitted (${G.slice(0,12)}...), waiting for dust...`)}if(X?.aborted)throw new Error("Operation cancelled");let V=(await w.firstValueFrom($.facade.state().pipe(w.throttleTime(5000),w.filter((J)=>J.isSynced),w.filter((J)=>J.dust.walletBalance(new Date)>0n),w.timeout(R0)))).dust.walletBalance(new Date);if(z.stop("Dust registration complete"),Q){let J={subcommand:"register",dustBalance:L0(V)};if(G)J.txHash=G;L(J);return}process.stdout.write(V.toString()+`
166
+ `),process.stderr.write(`
167
+ `+X0(`Dust tokens available: ${k0(V)}`)+`
168
+
169
+ `)}catch(Y){throw z.stop("Failed"),Y}}async function B$($,Z,Q,X,q){process.stderr.write(`
170
+ `+I("Dust Status")+`
171
+
172
+ `),process.stderr.write(H("Network",Z)+`
173
+
174
+ `);let z=v("Syncing wallet...");if(q)q.current=(Y,K)=>z.update(`Syncing wallet... (${K}, retrying)`);try{if(await I0($,(B,F)=>{if(F>0){let M=Math.round(B/F*100);z.update(`Syncing wallet... ${M}%`)}}),X?.aborted)throw new Error("Operation cancelled");z.update("Checking dust status...");let Y=await w.firstValueFrom($.facade.state().pipe(w.filter((B)=>B.isSynced))),K=Y.dust.walletBalance(new Date),G=Y.dust.availableCoins.length>0,U=Y.unshielded.availableCoins,V=U.filter((B)=>B.meta?.registeredForDustGeneration!==!0),J=U.length-V.length,W=Y.unshielded.balances[o3.unshieldedToken().raw]??0n;if(z.stop("Done"),Q){L({subcommand:"status",dustBalance:L0(K),registered:J,unregistered:V.length,nightBalance:O0(W),dustAvailable:G});return}process.stdout.write(`dust=${K}
175
+ `),process.stdout.write(`registered=${J}
176
+ `),process.stdout.write(`unregistered=${V.length}
177
+ `),process.stderr.write(H("NIGHT Balance",y(v0(W)))+`
178
+ `),process.stderr.write(H("Dust Balance",y(k0(K)))+`
179
+ `),process.stderr.write(H("Dust Available",G?"yes":"no")+`
180
+ `),process.stderr.write(H("Registered",J.toString()+" UTXO(s)")+`
181
+ `),process.stderr.write(H("Unregistered",V.length.toString()+" UTXO(s)")+`
182
+ `),process.stderr.write(`
183
+ `+D()+`
184
+
185
+ `)}catch(Y){throw z.stop("Failed"),Y}}var b1=O(()=>{Y0();s();_1();i0();N();B0()});var w1={};S(w1,{default:()=>a3});async function a3($){let Z=$.subcommand;if(!Z||Z!=="get"&&Z!=="set")throw new Error(`Usage: midnight config <get|set> <key> [value]
186
+ Valid keys: ${J1().join(", ")}`);let Q=$.positionals[0];if(!Q)throw new Error(`Missing config key.
187
+ Valid keys: ${J1().join(", ")}`);if(Z==="get"){let X=T3(Q);if(P($,"json")){L({action:"get",key:Q,value:X});return}process.stdout.write(X+`
188
+ `)}else{let X=$.positionals[1];if(X===void 0)throw new Error(`Missing value for config set.
189
+ Usage: midnight config set ${Q} <value>`);if(M3(Q,X),P($,"json")){L({action:"set",key:Q,value:X});return}process.stderr.write(o("✓")+` ${Q} = ${X}
190
+ `)}}var S1=O(()=>{K1()});import{execSync as _0}from"child_process";import{existsSync as t3,mkdirSync as V$,readFileSync as W$,writeFileSync as r3}from"fs";import{homedir as H$}from"os";import{join as f1}from"path";function e3(){try{return _0("docker compose version",{...n0,timeout:1e4}).trim()}catch{try{throw _0("docker --version",{...n0,timeout:5000}),new Error(`Docker Compose v2 is required.
191
+ Install it from https://docs.docker.com/compose/install/`)}catch($){if($ instanceof Error&&$.message.includes("Docker Compose v2"))throw $;throw new Error(`Docker is required but was not found.
192
+ Install Docker from https://docs.docker.com/get-docker/`)}}}function $2(){if(t3(C1)&&t3(o0)&&W$(C1,"utf-8").trim()===s3)return!1;return V$(h1,{recursive:!0,mode:Q0}),r3(o0,j$,"utf-8"),r3(C1,s3,"utf-8"),!0}function W0($){return _0(`docker compose -f "${o0}" ${$}`,n0)}function a0(){try{let $=W0("ps --format json");if(!$.trim())return[];let Z=$.trim().split(`
193
+ `),Q=[];for(let X of Z){if(!X.trim())continue;try{let q=JSON.parse(X),z=q.Service??"unknown";Q.push({name:z,state:q.State??"unknown",health:q.Health??"",port:F$[z]??""})}catch{}}return Q}catch{return[]}}function Z2($=120000,Z=3000){let Q=Date.now()+$;while(Date.now()<Q){let X=a0();if(X.length===3&&X.every((z)=>z.state==="running")){if(X.every((Y)=>Y.health==="healthy"||Y.health===""))return!0}_0(`sleep ${Z/1000}`,{timeout:Z+1000})}return!1}function p1(){return o0}function Q2(){let $=[];for(let Z of P$)try{_0(`docker rm -f "${Z}"`,{...n0,timeout:1e4}),$.push(Z)}catch{}return $}var s3="1.4.0",h1,o0,C1,j$=`services:
2261
194
  proof-server:
2262
195
  image: 'nel349/proof-server:7.0.0'
2263
196
  container_name: "proof-server"
@@ -2299,950 +232,84 @@ var COMPOSE_VERSION = "1.4.0", LOCALNET_DIR, COMPOSE_PATH, VERSION_PATH, COMPOSE
2299
232
  start_period: 5s
2300
233
  environment:
2301
234
  CFG_PRESET: "dev"
2302
- `, EXEC_OPTIONS, PORT_MAP, CONTAINER_NAMES;
2303
- var init_localnet = __esm(() => {
2304
- LOCALNET_DIR = join5(homedir5(), MIDNIGHT_DIR, LOCALNET_DIR_NAME);
2305
- COMPOSE_PATH = join5(LOCALNET_DIR, "compose.yml");
2306
- VERSION_PATH = join5(LOCALNET_DIR, ".version");
2307
- EXEC_OPTIONS = {
2308
- encoding: "utf-8",
2309
- timeout: 30000
2310
- };
2311
- PORT_MAP = {
2312
- node: "9944",
2313
- indexer: "8088",
2314
- "proof-server": "6300"
2315
- };
2316
- CONTAINER_NAMES = ["node", "indexer", "proof-server"];
2317
- });
2318
-
2319
- // src/commands/localnet.ts
2320
- var exports_localnet = {};
2321
- __export(exports_localnet, {
2322
- default: () => localnetCommand
2323
- });
2324
- import { spawn } from "child_process";
2325
- function isValidSubcommand(s) {
2326
- return VALID_SUBCOMMANDS.includes(s);
2327
- }
2328
- function formatServiceTable(services) {
2329
- const lines = [];
2330
- for (const svc of services) {
2331
- const stateColor = svc.state === "running" ? green : red;
2332
- const healthStr = svc.health ? ` (${svc.health})` : "";
2333
- const portStr = svc.port ? `:${svc.port}` : "";
2334
- lines.push(` ${svc.name.padEnd(16)}${stateColor(svc.state)}${dim(healthStr)}${dim(portStr)}`);
2335
- }
2336
- return lines.join(`
2337
- `);
2338
- }
2339
- async function handleUp(jsonMode) {
2340
- const wrote = ensureComposeFile();
2341
- if (wrote) {
2342
- process.stderr.write(dim(` Wrote compose.yml to ${getComposePath()}`) + `
2343
- `);
2344
- }
2345
- const spinner = start("Starting local network...");
2346
- try {
2347
- dockerCompose("up -d");
2348
- spinner.update("Waiting for services to be healthy...");
2349
- const healthy = waitForHealthy(120000);
2350
- if (!healthy) {
2351
- spinner.stop(yellow("Services started but not all healthy yet"));
2352
- process.stderr.write(`
2353
- ` + dim(" Tip: run ") + bold("midnight localnet logs") + dim(" to check for errors") + `
2354
- `);
2355
- } else {
2356
- spinner.stop("Local network is running");
2357
- }
2358
- } catch (err) {
2359
- spinner.stop(red("Failed to start local network"));
2360
- if (err instanceof Error) {
2361
- if (err.message.includes("is already in use by container")) {
2362
- throw new Error(`Container name conflict — containers with the same names already exist
2363
- ` + `(likely from a previous midnight-local-network setup).
2364
-
2365
- ` + 'Run "midnight localnet clean" to remove them, then try again.');
2366
- }
2367
- if (err.message.includes("address already in use")) {
2368
- throw new Error(`Port conflict detected — another process is using a required port.
2369
- ` + "Check ports 9944, 8088, and 6300, then try again.");
2370
- }
2371
- }
2372
- throw err;
2373
- }
2374
- const services = getServiceStatus();
2375
- if (jsonMode) {
2376
- writeJsonResult({
2377
- subcommand: "up",
2378
- services: services.map((s) => ({ name: s.name, state: s.state, port: s.port, health: s.health }))
2379
- });
2380
- return;
2381
- }
2382
- if (services.length > 0) {
2383
- process.stderr.write(`
2384
- ` + formatServiceTable(services) + `
2385
- `);
2386
- }
2387
- for (const svc of services) {
2388
- process.stdout.write(`${svc.name}=${svc.state}:${svc.port}
2389
- `);
2390
- }
2391
- process.stderr.write(`
2392
- ` + dim(" Next: ") + bold("midnight generate --network undeployed") + `
2393
- `);
2394
- }
2395
- async function handleStop(jsonMode) {
2396
- const spinner = start("Stopping local network...");
2397
- try {
2398
- dockerCompose("stop");
2399
- spinner.stop("Local network stopped (containers preserved)");
2400
- if (jsonMode) {
2401
- writeJsonResult({ subcommand: "stop", status: "stopped" });
2402
- return;
2403
- }
2404
- } catch (err) {
2405
- spinner.stop(red("Failed to stop local network"));
2406
- throw err;
2407
- }
2408
- }
2409
- async function handleDown(jsonMode) {
2410
- const spinner = start("Tearing down local network...");
2411
- try {
2412
- dockerCompose("down --volumes");
2413
- spinner.stop("Local network removed (containers, networks, volumes)");
2414
- if (jsonMode) {
2415
- writeJsonResult({ subcommand: "down", status: "removed" });
2416
- return;
2417
- }
2418
- } catch (err) {
2419
- spinner.stop(red("Failed to tear down local network"));
2420
- throw err;
2421
- }
2422
- }
2423
- async function handleStatus(jsonMode) {
2424
- const services = getServiceStatus();
2425
- if (jsonMode) {
2426
- writeJsonResult({
2427
- subcommand: "status",
2428
- services: services.map((s) => ({ name: s.name, state: s.state, port: s.port, health: s.health }))
2429
- });
2430
- return;
2431
- }
2432
- if (services.length === 0) {
2433
- process.stderr.write(`
2434
- ` + header("Localnet Status") + `
2435
-
2436
- `);
2437
- process.stderr.write(dim(" No services running.") + `
2438
- `);
2439
- process.stderr.write(dim(" Run ") + bold("midnight localnet up") + dim(" to start.") + `
2440
-
2441
- `);
2442
- return;
2443
- }
2444
- process.stderr.write(`
2445
- ` + header("Localnet Status") + `
2446
-
2447
- `);
2448
- process.stderr.write(formatServiceTable(services) + `
2449
- `);
2450
- process.stderr.write(`
2451
- ` + divider() + `
2452
-
2453
- `);
2454
- for (const svc of services) {
2455
- process.stdout.write(`${svc.name}=${svc.state}:${svc.port}
2456
- `);
2457
- }
2458
- }
2459
- async function handleClean(jsonMode) {
2460
- const spinner = start("Removing conflicting containers...");
2461
- try {
2462
- try {
2463
- dockerCompose("down");
2464
- } catch {
2465
- }
2466
- const removed = removeConflictingContainers();
2467
- if (removed.length > 0) {
2468
- spinner.stop(`Removed ${removed.length} container${removed.length > 1 ? "s" : ""}: ${removed.join(", ")}`);
2469
- } else {
2470
- spinner.stop("No conflicting containers found");
2471
- }
2472
- if (jsonMode) {
2473
- writeJsonResult({ subcommand: "clean", status: "cleaned", removed });
2474
- return;
2475
- }
2476
- } catch (err) {
2477
- spinner.stop(red("Failed to clean up"));
2478
- throw err;
2479
- }
2480
- }
2481
- async function handleLogs() {
2482
- const composePath = getComposePath();
2483
- const child = spawn("docker", ["compose", "-f", composePath, "logs", "-f"], {
2484
- stdio: "inherit"
2485
- });
2486
- return new Promise((resolve4, reject) => {
2487
- child.on("close", (code) => {
2488
- if (code === 0 || code === 130 || code === null) {
2489
- resolve4();
2490
- } else {
2491
- reject(new Error(`docker compose logs exited with code ${code}`));
2492
- }
2493
- });
2494
- child.on("error", reject);
2495
- });
2496
- }
2497
- async function localnetCommand(args) {
2498
- const subcommand = args.subcommand;
2499
- if (!subcommand || !isValidSubcommand(subcommand)) {
2500
- throw new Error(`Usage: midnight localnet <${VALID_SUBCOMMANDS.join("|")}>
2501
-
2502
- ` + `Subcommands:
2503
- ` + ` up Start the local network
2504
- ` + ` stop Stop containers (preserves state)
2505
- ` + ` down Remove containers, networks, volumes
2506
- ` + ` status Show service status
2507
- ` + ` logs Stream service logs
2508
- ` + ` clean Remove conflicting containers
2509
-
2510
- ` + `Example: midnight localnet up`);
2511
- }
2512
- checkDockerAvailable();
2513
- const jsonMode = hasFlag(args, "json");
2514
- process.stderr.write(`
2515
- ` + header("Localnet") + `
2516
-
2517
- `);
2518
- switch (subcommand) {
2519
- case "up":
2520
- return handleUp(jsonMode);
2521
- case "stop":
2522
- return handleStop(jsonMode);
2523
- case "down":
2524
- return handleDown(jsonMode);
2525
- case "status":
2526
- return handleStatus(jsonMode);
2527
- case "logs":
2528
- return handleLogs();
2529
- case "clean":
2530
- return handleClean(jsonMode);
2531
- }
2532
- }
2533
- var VALID_SUBCOMMANDS;
2534
- var init_localnet2 = __esm(() => {
2535
- init_localnet();
2536
- init_format();
2537
- init_spinner();
2538
- VALID_SUBCOMMANDS = ["up", "stop", "down", "status", "logs", "clean"];
2539
- });
2540
-
2541
- // src/mcp-server.ts
2542
- var exports_mcp_server = {};
2543
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2544
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
2545
- import { ListToolsRequestSchema, CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
2546
- function buildArgs(command, params, subcommand) {
2547
- const flags = { json: true };
2548
- const positionals = [];
2549
- for (const [key, value] of Object.entries(params)) {
2550
- if (value === undefined || value === null)
2551
- continue;
2552
- if (typeof value === "boolean") {
2553
- if (value)
2554
- flags[key] = true;
2555
- } else {
2556
- flags[key] = String(value);
2557
- }
2558
- }
2559
- return {
2560
- command,
2561
- subcommand,
2562
- positionals,
2563
- flags
2564
- };
2565
- }
2566
- async function importHandler(name) {
2567
- const loader = handlerLoaders[name];
2568
- if (!loader)
2569
- throw new Error(`Unknown command handler: ${name}`);
2570
- const mod = await loader();
2571
- return mod.default;
2572
- }
2573
- async function main() {
2574
- const transport = new StdioServerTransport;
2575
- await server.connect(transport);
2576
- }
2577
- var handlerLoaders, TOOLS, server;
2578
- var init_mcp_server = __esm(() => {
2579
- init_run_command();
2580
- init_exit_codes();
2581
- init_pkg();
2582
- handlerLoaders = {
2583
- generate: () => Promise.resolve().then(() => (init_generate(), exports_generate)),
2584
- info: () => Promise.resolve().then(() => (init_info(), exports_info)),
2585
- balance: () => Promise.resolve().then(() => (init_balance(), exports_balance)),
2586
- address: () => Promise.resolve().then(() => (init_address(), exports_address)),
2587
- "genesis-address": () => Promise.resolve().then(() => (init_genesis_address(), exports_genesis_address)),
2588
- "inspect-cost": () => Promise.resolve().then(() => (init_inspect_cost(), exports_inspect_cost)),
2589
- airdrop: () => Promise.resolve().then(() => (init_airdrop(), exports_airdrop)),
2590
- transfer: () => Promise.resolve().then(() => (init_transfer2(), exports_transfer)),
2591
- dust: () => Promise.resolve().then(() => (init_dust(), exports_dust)),
2592
- config: () => Promise.resolve().then(() => (init_config(), exports_config)),
2593
- localnet: () => Promise.resolve().then(() => (init_localnet2(), exports_localnet))
2594
- };
2595
- TOOLS = [
2596
- {
2597
- name: "midnight_generate",
2598
- description: "Generate a new wallet (random mnemonic, or restore from seed/mnemonic)",
2599
- inputSchema: {
2600
- type: "object",
2601
- properties: {
2602
- network: { type: "string", description: "Network: preprod, preview, undeployed", enum: ["preprod", "preview", "undeployed"] },
2603
- seed: { type: "string", description: "Restore from existing seed (64-char hex)" },
2604
- mnemonic: { type: "string", description: "Restore from BIP-39 mnemonic (24 words)" },
2605
- output: { type: "string", description: "Custom output path (default: ~/.midnight/wallet.json)" },
2606
- force: { type: "string", description: 'Set to "true" to overwrite existing wallet file' }
2607
- }
2608
- },
2609
- async handler(params) {
2610
- const args = buildArgs("generate", params);
2611
- if (params.force === "true" || params.force === true)
2612
- args.flags.force = true;
2613
- const handler = await importHandler("generate");
2614
- return captureCommand(handler, args);
2615
- }
2616
- },
2617
- {
2618
- name: "midnight_info",
2619
- description: "Display wallet address, network, creation date (no secrets shown)",
2620
- inputSchema: {
2621
- type: "object",
2622
- properties: {
2623
- wallet: { type: "string", description: "Custom wallet file path" }
2624
- }
2625
- },
2626
- async handler(params) {
2627
- const args = buildArgs("info", params);
2628
- const handler = await importHandler("info");
2629
- return captureCommand(handler, args);
2630
- }
2631
- },
2632
- {
2633
- name: "midnight_balance",
2634
- description: "Check unshielded balance via indexer subscription",
2635
- inputSchema: {
2636
- type: "object",
2637
- properties: {
2638
- address: { type: "string", description: "Address to check (or reads from wallet file)" },
2639
- wallet: { type: "string", description: "Custom wallet file path" },
2640
- network: { type: "string", description: "Override network detection", enum: ["preprod", "preview", "undeployed"] },
2641
- "indexer-ws": { type: "string", description: "Custom indexer WebSocket URL" }
2642
- }
2643
- },
2644
- async handler(params) {
2645
- const address = params.address;
2646
- const args = buildArgs("balance", params, address);
2647
- delete args.flags.address;
2648
- const handler = await importHandler("balance");
2649
- return captureCommand(handler, args);
2650
- }
2651
- },
2652
- {
2653
- name: "midnight_address",
2654
- description: "Derive and display an unshielded address from a seed",
2655
- inputSchema: {
2656
- type: "object",
2657
- properties: {
2658
- seed: { type: "string", description: "Seed to derive from (required, 64-char hex)" },
2659
- network: { type: "string", description: "Network for address prefix", enum: ["preprod", "preview", "undeployed"] },
2660
- index: { type: "string", description: "Key derivation index (default: 0)" }
2661
- },
2662
- required: ["seed"]
2663
- },
2664
- async handler(params) {
2665
- const args = buildArgs("address", params);
2666
- const handler = await importHandler("address");
2667
- return captureCommand(handler, args);
2668
- }
2669
- },
2670
- {
2671
- name: "midnight_genesis_address",
2672
- description: "Display the genesis wallet address (seed 0x01) for a network",
2673
- inputSchema: {
2674
- type: "object",
2675
- properties: {
2676
- network: { type: "string", description: "Network for address prefix", enum: ["preprod", "preview", "undeployed"] }
2677
- }
2678
- },
2679
- async handler(params) {
2680
- const args = buildArgs("genesis-address", params);
2681
- const handler = await importHandler("genesis-address");
2682
- return captureCommand(handler, args);
2683
- }
2684
- },
2685
- {
2686
- name: "midnight_inspect_cost",
2687
- description: "Display current block limits derived from LedgerParameters",
2688
- inputSchema: {
2689
- type: "object",
2690
- properties: {}
2691
- },
2692
- async handler() {
2693
- const args = buildArgs("inspect-cost", {});
2694
- const handler = await importHandler("inspect-cost");
2695
- return captureCommand(handler, args);
2696
- }
2697
- },
2698
- {
2699
- name: "midnight_airdrop",
2700
- description: "Fund your wallet from the genesis wallet (undeployed network only)",
2701
- inputSchema: {
2702
- type: "object",
2703
- properties: {
2704
- amount: { type: "string", description: "Amount in NIGHT to airdrop" },
2705
- wallet: { type: "string", description: "Custom wallet file path" }
2706
- },
2707
- required: ["amount"]
2708
- },
2709
- async handler(params) {
2710
- const amount = params.amount;
2711
- const args = buildArgs("airdrop", params, amount);
2712
- delete args.flags.amount;
2713
- const handler = await importHandler("airdrop");
2714
- return captureCommand(handler, args);
2715
- }
2716
- },
2717
- {
2718
- name: "midnight_transfer",
2719
- description: "Send NIGHT tokens to another address",
2720
- inputSchema: {
2721
- type: "object",
2722
- properties: {
2723
- to: { type: "string", description: "Recipient bech32m address" },
2724
- amount: { type: "string", description: "Amount in NIGHT to send" },
2725
- wallet: { type: "string", description: "Custom wallet file path" }
2726
- },
2727
- required: ["to", "amount"]
2728
- },
2729
- async handler(params) {
2730
- const to = params.to;
2731
- const amount = params.amount;
2732
- const args = buildArgs("transfer", params, to);
2733
- args.positionals = [amount];
2734
- delete args.flags.to;
2735
- delete args.flags.amount;
2736
- const handler = await importHandler("transfer");
2737
- return captureCommand(handler, args);
2738
- }
2739
- },
2740
- {
2741
- name: "midnight_dust_register",
2742
- description: "Register NIGHT UTXOs for dust (fee token) generation",
2743
- inputSchema: {
2744
- type: "object",
2745
- properties: {
2746
- wallet: { type: "string", description: "Custom wallet file path" }
2747
- }
2748
- },
2749
- async handler(params) {
2750
- const args = buildArgs("dust", params, "register");
2751
- const handler = await importHandler("dust");
2752
- return captureCommand(handler, args);
2753
- }
2754
- },
2755
- {
2756
- name: "midnight_dust_status",
2757
- description: "Check dust registration status and balance",
2758
- inputSchema: {
2759
- type: "object",
2760
- properties: {
2761
- wallet: { type: "string", description: "Custom wallet file path" }
2762
- }
2763
- },
2764
- async handler(params) {
2765
- const args = buildArgs("dust", params, "status");
2766
- const handler = await importHandler("dust");
2767
- return captureCommand(handler, args);
2768
- }
2769
- },
2770
- {
2771
- name: "midnight_config_get",
2772
- description: "Read a persistent config value",
2773
- inputSchema: {
2774
- type: "object",
2775
- properties: {
2776
- key: { type: "string", description: 'Config key to read (e.g. "network")' }
2777
- },
2778
- required: ["key"]
2779
- },
2780
- async handler(params) {
2781
- const key = params.key;
2782
- const args = {
2783
- command: "config",
2784
- subcommand: "get",
2785
- positionals: [key],
2786
- flags: { json: true }
2787
- };
2788
- const handler = await importHandler("config");
2789
- return captureCommand(handler, args);
2790
- }
2791
- },
2792
- {
2793
- name: "midnight_config_set",
2794
- description: "Write a persistent config value",
2795
- inputSchema: {
2796
- type: "object",
2797
- properties: {
2798
- key: { type: "string", description: 'Config key to set (e.g. "network")' },
2799
- value: { type: "string", description: "Config value to set" }
2800
- },
2801
- required: ["key", "value"]
2802
- },
2803
- async handler(params) {
2804
- const key = params.key;
2805
- const value = params.value;
2806
- const args = {
2807
- command: "config",
2808
- subcommand: "set",
2809
- positionals: [key, value],
2810
- flags: { json: true }
2811
- };
2812
- const handler = await importHandler("config");
2813
- return captureCommand(handler, args);
2814
- }
2815
- },
2816
- {
2817
- name: "midnight_localnet_up",
2818
- description: "Start a local Midnight network via Docker Compose",
2819
- inputSchema: {
2820
- type: "object",
2821
- properties: {}
2822
- },
2823
- async handler() {
2824
- const args = {
2825
- command: "localnet",
2826
- subcommand: "up",
2827
- positionals: [],
2828
- flags: { json: true }
2829
- };
2830
- const handler = await importHandler("localnet");
2831
- return captureCommand(handler, args);
2832
- }
2833
- },
2834
- {
2835
- name: "midnight_localnet_stop",
2836
- description: "Stop local network containers (preserves state for fast restart)",
2837
- inputSchema: {
2838
- type: "object",
2839
- properties: {}
2840
- },
2841
- async handler() {
2842
- const args = {
2843
- command: "localnet",
2844
- subcommand: "stop",
2845
- positionals: [],
2846
- flags: { json: true }
2847
- };
2848
- const handler = await importHandler("localnet");
2849
- return captureCommand(handler, args);
2850
- }
2851
- },
2852
- {
2853
- name: "midnight_localnet_down",
2854
- description: "Remove local network containers, networks, and volumes (full teardown)",
2855
- inputSchema: {
2856
- type: "object",
2857
- properties: {}
2858
- },
2859
- async handler() {
2860
- const args = {
2861
- command: "localnet",
2862
- subcommand: "down",
2863
- positionals: [],
2864
- flags: { json: true }
2865
- };
2866
- const handler = await importHandler("localnet");
2867
- return captureCommand(handler, args);
2868
- }
2869
- },
2870
- {
2871
- name: "midnight_localnet_status",
2872
- description: "Show local network service status and ports",
2873
- inputSchema: {
2874
- type: "object",
2875
- properties: {}
2876
- },
2877
- async handler() {
2878
- const args = {
2879
- command: "localnet",
2880
- subcommand: "status",
2881
- positionals: [],
2882
- flags: { json: true }
2883
- };
2884
- const handler = await importHandler("localnet");
2885
- return captureCommand(handler, args);
2886
- }
2887
- },
2888
- {
2889
- name: "midnight_localnet_clean",
2890
- description: "Remove conflicting containers from other setups",
2891
- inputSchema: {
2892
- type: "object",
2893
- properties: {}
2894
- },
2895
- async handler() {
2896
- const args = {
2897
- command: "localnet",
2898
- subcommand: "clean",
2899
- positionals: [],
2900
- flags: { json: true }
2901
- };
2902
- const handler = await importHandler("localnet");
2903
- return captureCommand(handler, args);
2904
- }
2905
- }
2906
- ];
2907
- server = new Server({ name: "midnight-wallet-cli", version: PKG_VERSION }, { capabilities: { tools: {} } });
2908
- server.setRequestHandler(ListToolsRequestSchema, async () => {
2909
- return {
2910
- tools: TOOLS.map((t) => ({
2911
- name: t.name,
2912
- description: t.description,
2913
- inputSchema: t.inputSchema
2914
- }))
2915
- };
2916
- });
2917
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
2918
- const { name, arguments: params } = request.params;
2919
- const tool = TOOLS.find((t) => t.name === name);
2920
- if (!tool) {
2921
- return {
2922
- content: [{ type: "text", text: `Unknown tool: ${name}` }],
2923
- isError: true
2924
- };
2925
- }
2926
- try {
2927
- const result = await tool.handler(params ?? {});
2928
- return {
2929
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
2930
- };
2931
- } catch (err) {
2932
- const error = err instanceof Error ? err : new Error(String(err));
2933
- const { errorCode } = classifyError(error);
2934
- return {
2935
- content: [{
2936
- type: "text",
2937
- text: JSON.stringify({ error: true, code: errorCode, message: error.message })
2938
- }],
2939
- isError: true
2940
- };
2941
- }
2942
- });
2943
- main().catch((err) => {
2944
- process.stderr.write(`MCP server error: ${err.message}
2945
- `);
2946
- process.exit(1);
2947
- });
2948
- });
2949
-
2950
- // src/ui/art.ts
2951
- function getWordmarkTypingFrame(progress) {
2952
- const clamped = Math.max(0, Math.min(1, progress));
2953
- const width = WORDMARK_BIG[0].length;
2954
- const visibleCols = Math.floor(clamped * width);
2955
- return WORDMARK_BIG.map((line) => line.slice(0, visibleCols).padEnd(width));
2956
- }
2957
- function getWordmarkMaterializeFrame(progress) {
2958
- const clamped = Math.max(0, Math.min(1, progress));
2959
- const seed = Math.floor(progress * 100);
2960
- if (clamped >= 1)
2961
- return WORDMARK_BIG;
2962
- return WORDMARK_BIG.map((line, row) => Array.from(line).map((ch, col) => {
2963
- if (ch === " ")
2964
- return " ";
2965
- if (clamped <= 0)
2966
- return noiseChar(row + 20, col, 0);
2967
- const threshold = ((row + 20) * 131 + col * 997) % 100 / 100;
2968
- return clamped >= threshold ? ch : noiseChar(row + 20, col, seed);
2969
- }).join(""));
2970
- }
2971
- function noiseChar(row, col, seed) {
2972
- const hash = (row * 131 + col * 997 + seed * 7919) % 65537 / 65537;
2973
- return NOISE_CHARS[Math.floor(hash * NOISE_CHARS.length)];
2974
- }
2975
- function getMaterializeFrame(progress) {
2976
- const clamped = Math.max(0, Math.min(1, progress));
2977
- const lines = MIDNIGHT_LOGO.split(`
2978
- `);
2979
- const seed = Math.floor(progress * 100);
2980
- if (clamped >= 1)
2981
- return MIDNIGHT_LOGO;
2982
- if (clamped <= 0) {
2983
- return lines.map((line, row) => Array.from(line).map((_, col) => noiseChar(row, col, 0)).join("")).join(`
2984
- `);
2985
- }
2986
- return lines.map((line, row) => Array.from(line).map((ch, col) => {
2987
- if (ch === " ")
2988
- return " ";
2989
- const threshold = (row * 131 + col * 997) % 100 / 100;
2990
- return clamped >= threshold ? ch : noiseChar(row, col, seed);
2991
- }).join("")).join(`
2992
- `);
2993
- }
2994
- var MIDNIGHT_LOGO, WORDMARK_BIG, COMMAND_BRIEFS, NOISE_CHARS;
2995
- var init_art = __esm(() => {
2996
- MIDNIGHT_LOGO = [
2997
- " ████████████ ",
2998
- " ███ ███ ",
2999
- " ███ ██ ███ ",
3000
- " ██ ██ ",
3001
- " ██ ██ ██ ",
3002
- " ██ ██ ",
3003
- " ██ ██ ██ ",
3004
- " ██ ██ ",
3005
- " ██ ██ ",
3006
- " ██ ██ ",
3007
- " ██ ██ ",
3008
- " ███ ███ ",
3009
- " ███ ███ ",
3010
- " ████████████ "
3011
- ].join(`
3012
- `);
3013
- WORDMARK_BIG = [
3014
- "█▄ ▄█ █ █▀▄ █▄ █ █ █▀▀ █ █ ▀█▀",
3015
- "█ █ █ █ █ █ █ ██ █ █ █ █▀█ █ ",
3016
- "▀ ▀ ▀ ▀▀ ▀ ▀ ▀ ▀▀▀ ▀ ▀ ▀ "
3017
- ];
3018
- COMMAND_BRIEFS = [
3019
- ["generate", "Generate or restore a wallet"],
3020
- ["info", "Display wallet metadata"],
3021
- ["balance", "Check unshielded balance"],
3022
- ["address", "Derive address from seed"],
3023
- ["genesis-address", "Show genesis address"],
3024
- ["inspect-cost", "Display block limits"],
3025
- ["airdrop", "Fund from genesis wallet"],
3026
- ["transfer", "Send NIGHT tokens"],
3027
- ["dust", "Manage dust (fee tokens)"],
3028
- ["config", "Manage CLI config"],
3029
- ["localnet", "Manage local network"],
3030
- ["help", "Show command usage"]
3031
- ];
3032
- NOISE_CHARS = ["░", "▒", "▓", "█", "·", " "];
3033
- });
3034
-
3035
- // src/ui/animate.ts
3036
- function sleep(ms, signal) {
3037
- return new Promise((resolve4, reject) => {
3038
- if (signal?.aborted) {
3039
- resolve4();
3040
- return;
3041
- }
3042
- const timer = setTimeout(resolve4, ms);
3043
- signal?.addEventListener("abort", () => {
3044
- clearTimeout(timer);
3045
- resolve4();
3046
- }, { once: true });
3047
- });
3048
- }
3049
- async function animateMaterialize(signal, sideContent) {
3050
- const totalFrames = 20;
3051
- const logoLines = MIDNIGHT_LOGO.split(`
3052
- `);
3053
- const logoLineCount = logoLines.length;
3054
- const rightCol = 36;
3055
- const totalHeight = Math.max(logoLineCount, sideContent?.length ?? 0);
3056
- const wordmarkLineCount = 3;
3057
- if (!isColorEnabled()) {
3058
- for (let j = 0;j < totalHeight; j++) {
3059
- const left = (j < logoLineCount ? logoLines[j] : "").padEnd(rightCol - 1);
3060
- const right = sideContent?.[j] ?? "";
3061
- process.stderr.write(left + right + `
3062
- `);
3063
- }
3064
- return;
3065
- }
3066
- function renderFrame(frameLogoLines, rightLines) {
3067
- for (let j = 0;j < totalHeight; j++) {
3068
- const left = j < frameLogoLines.length ? white(frameLogoLines[j]) : "";
3069
- const right = rightLines[j] ?? "";
3070
- if (right) {
3071
- process.stderr.write(left + `\x1B[${rightCol}G` + right + `\x1B[K
3072
- `);
3073
- } else {
3074
- process.stderr.write(left + `\x1B[K
3075
- `);
3076
- }
3077
- }
3078
- }
3079
- function moveUp() {
3080
- process.stderr.write(`\x1B[${totalHeight}A`);
3081
- }
3082
- for (let i = 0;i <= totalFrames; i++) {
3083
- if (signal?.aborted)
3084
- break;
3085
- const progress = i / totalFrames;
3086
- const frame = getMaterializeFrame(progress);
3087
- const frameLines = frame.split(`
3088
- `);
3089
- if (i > 0)
3090
- moveUp();
3091
- renderFrame(frameLines, []);
3092
- await sleep(FRAME_MS, signal);
3093
- }
3094
- const typingFrames = 20;
3095
- for (let i = 0;i <= typingFrames; i++) {
3096
- if (signal?.aborted)
3097
- break;
3098
- const progress = i / typingFrames;
3099
- const typedLines = getWordmarkTypingFrame(progress);
3100
- moveUp();
3101
- const rightLines = new Array(totalHeight).fill(null);
3102
- for (let j = 0;j < typedLines.length; j++) {
3103
- rightLines[j] = bold(white(typedLines[j]));
3104
- }
3105
- renderFrame(logoLines, rightLines);
3106
- await sleep(FRAME_MS, signal);
3107
- }
3108
- const flashFrames = 12;
3109
- for (let i = 0;i <= flashFrames; i++) {
3110
- if (signal?.aborted)
3111
- break;
3112
- const progress = i / flashFrames;
3113
- const flashedLines = getWordmarkMaterializeFrame(progress);
3114
- moveUp();
3115
- const rightLines = new Array(totalHeight).fill(null);
3116
- for (let j = 0;j < flashedLines.length; j++) {
3117
- rightLines[j] = bold(white(flashedLines[j]));
3118
- }
3119
- renderFrame(logoLines, rightLines);
3120
- await sleep(FRAME_MS, signal);
3121
- }
3122
- moveUp();
3123
- const fullRight = new Array(totalHeight).fill(null);
3124
- if (sideContent) {
3125
- for (let j = 0;j < sideContent.length; j++) {
3126
- if (j < wordmarkLineCount) {
3127
- fullRight[j] = bold(white(sideContent[j]));
3128
- } else {
3129
- fullRight[j] = sideContent[j];
3130
- }
3131
- }
3132
- }
3133
- renderFrame(logoLines, fullRight);
3134
- }
3135
- var FRAME_MS = 80;
3136
- var init_animate = __esm(() => {
3137
- init_art();
3138
- });
3139
-
3140
- // src/commands/help.ts
3141
- var exports_help = {};
3142
- __export(exports_help, {
3143
- default: () => helpCommand,
3144
- COMMAND_SPECS: () => COMMAND_SPECS
3145
- });
3146
- function buildRightColumn() {
3147
- const lines = [];
3148
- for (const wl of WORDMARK_BIG) {
3149
- lines.push(wl);
3150
- }
3151
- lines.push("");
3152
- lines.push(bold("Commands"));
3153
- for (const [name, brief] of COMMAND_BRIEFS) {
3154
- lines.push(`${teal(name.padEnd(18))}${brief}`);
3155
- }
3156
- lines.push("");
3157
- lines.push(dim(`midnight (or mn) help <command>`));
3158
- lines.push(dim(`--json flag available on all commands`));
3159
- lines.push(dim(`midnight help --agent`) + dim(` AI & MCP reference`));
3160
- return lines;
3161
- }
3162
- function printPlainHelp() {
3163
- process.stderr.write(`
235
+ `,n0,F$,P$;var X2=O(()=>{h1=f1(H$(),m,z3),o0=f1(h1,"compose.yml"),C1=f1(h1,".version"),n0={encoding:"utf-8",timeout:30000};F$={node:"9944",indexer:"8088","proof-server":"6300"};P$=["node","indexer","proof-server"]});var u1={};S(u1,{default:()=>Y2});import{spawn as O$}from"child_process";function L$($){return q2.includes($)}function z2($){let Z=[];for(let Q of $){let X=Q.state==="running"?o:f,q=Q.health?` (${Q.health})`:"",z=Q.port?`:${Q.port}`:"";Z.push(` ${Q.name.padEnd(16)}${X(Q.state)}${j(q)}${j(z)}`)}return Z.join(`
236
+ `)}async function y$($){if($2())process.stderr.write(j(` Wrote compose.yml to ${p1()}`)+`
237
+ `);let Q=v("Starting local network...");try{if(W0("up -d"),Q.update("Waiting for services to be healthy..."),!Z2(120000))Q.stop(j0("Services started but not all healthy yet")),process.stderr.write(`
238
+ `+j(" Tip: run ")+y("midnight localnet logs")+j(" to check for errors")+`
239
+ `);else Q.stop("Local network is running")}catch(q){if(Q.stop(f("Failed to start local network")),q instanceof Error){if(q.message.includes("is already in use by container"))throw new Error(`Container name conflict — containers with the same names already exist
240
+ `+`(likely from a previous midnight-local-network setup).
241
+
242
+ Run "midnight localnet clean" to remove them, then try again.`);if(q.message.includes("address already in use"))throw new Error(`Port conflict detected — another process is using a required port.
243
+ `+"Check ports 9944, 8088, and 6300, then try again.")}throw q}let X=a0();if($){L({subcommand:"up",services:X.map((q)=>({name:q.name,state:q.state,port:q.port,health:q.health}))});return}if(X.length>0)process.stderr.write(`
244
+ `+z2(X)+`
245
+ `);for(let q of X)process.stdout.write(`${q.name}=${q.state}:${q.port}
246
+ `);process.stderr.write(`
247
+ `+j(" Next: ")+y("midnight generate --network undeployed")+`
248
+ `)}async function T$($){let Z=v("Stopping local network...");try{if(W0("stop"),Z.stop("Local network stopped (containers preserved)"),$){L({subcommand:"stop",status:"stopped"});return}}catch(Q){throw Z.stop(f("Failed to stop local network")),Q}}async function M$($){let Z=v("Tearing down local network...");try{if(W0("down --volumes"),Z.stop("Local network removed (containers, networks, volumes)"),$){L({subcommand:"down",status:"removed"});return}}catch(Q){throw Z.stop(f("Failed to tear down local network")),Q}}async function I$($){let Z=a0();if($){L({subcommand:"status",services:Z.map((Q)=>({name:Q.name,state:Q.state,port:Q.port,health:Q.health}))});return}if(Z.length===0){process.stderr.write(`
249
+ `+I("Localnet Status")+`
250
+
251
+ `),process.stderr.write(j(" No services running.")+`
252
+ `),process.stderr.write(j(" Run ")+y("midnight localnet up")+j(" to start.")+`
253
+
254
+ `);return}process.stderr.write(`
255
+ `+I("Localnet Status")+`
256
+
257
+ `),process.stderr.write(z2(Z)+`
258
+ `),process.stderr.write(`
259
+ `+D()+`
260
+
261
+ `);for(let Q of Z)process.stdout.write(`${Q.name}=${Q.state}:${Q.port}
262
+ `)}async function _$($){let Z=v("Removing conflicting containers...");try{try{W0("down")}catch{}let Q=Q2();if(Q.length>0)Z.stop(`Removed ${Q.length} container${Q.length>1?"s":""}: ${Q.join(", ")}`);else Z.stop("No conflicting containers found");if($){L({subcommand:"clean",status:"cleaned",removed:Q});return}}catch(Q){throw Z.stop(f("Failed to clean up")),Q}}async function A$(){let $=p1(),Z=O$("docker",["compose","-f",$,"logs","-f"],{stdio:"inherit"});return new Promise((Q,X)=>{Z.on("close",(q)=>{if(q===0||q===130||q===null)Q();else X(new Error(`docker compose logs exited with code ${q}`))}),Z.on("error",X)})}async function Y2($){let Z=$.subcommand;if(!Z||!L$(Z))throw new Error(`Usage: midnight localnet <${q2.join("|")}>
263
+
264
+ Subcommands:
265
+ up Start the local network
266
+ stop Stop containers (preserves state)
267
+ down Remove containers, networks, volumes
268
+ status Show service status
269
+ logs Stream service logs
270
+ clean Remove conflicting containers
271
+
272
+ Example: midnight localnet up`);e3();let Q=P($,"json");switch(process.stderr.write(`
273
+ `+I("Localnet")+`
274
+
275
+ `),Z){case"up":return y$(Q);case"stop":return T$(Q);case"down":return M$(Q);case"status":return I$(Q);case"logs":return A$();case"clean":return _$(Q)}}var q2;var c1=O(()=>{X2();N();B0();q2=["up","stop","down","status","logs","clean"]});var k$={};import{Server as D$}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as R$}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as x$,CallToolRequestSchema as E$}from"@modelcontextprotocol/sdk/types.js";function l($,Z,Q){let X={json:!0},q=[];for(let[z,Y]of Object.entries(Z)){if(Y===void 0||Y===null)continue;if(typeof Y==="boolean"){if(Y)X[z]=!0}else X[z]=String(Y)}return{command:$,subcommand:Q,positionals:q,flags:X}}async function x($){let Z=N$[$];if(!Z)throw new Error(`Unknown command handler: ${$}`);return(await Z()).default}async function v$(){let $=new R$;await m1.connect($)}var N$,J2,m1;var K2=O(()=>{H3();Z1();w0();N$={generate:()=>Promise.resolve().then(() => (U1(),G1)),info:()=>Promise.resolve().then(() => (V1(),B1)),balance:()=>Promise.resolve().then(() => (H1(),W1)),address:()=>Promise.resolve().then(() => (F1(),j1)),"genesis-address":()=>Promise.resolve().then(() => (O1(),P1)),"inspect-cost":()=>Promise.resolve().then(() => (y1(),L1)),airdrop:()=>Promise.resolve().then(() => (E1(),x1)),transfer:()=>Promise.resolve().then(() => (v1(),N1)),dust:()=>Promise.resolve().then(() => (b1(),k1)),config:()=>Promise.resolve().then(() => (S1(),w1)),localnet:()=>Promise.resolve().then(() => (c1(),u1))};J2=[{name:"midnight_generate",description:"Generate a new wallet (random mnemonic, or restore from seed/mnemonic)",inputSchema:{type:"object",properties:{network:{type:"string",description:"Network: preprod, preview, undeployed",enum:["preprod","preview","undeployed"]},seed:{type:"string",description:"Restore from existing seed (64-char hex)"},mnemonic:{type:"string",description:"Restore from BIP-39 mnemonic (24 words)"},output:{type:"string",description:"Custom output path (default: ~/.midnight/wallet.json)"},force:{type:"string",description:'Set to "true" to overwrite existing wallet file'}}},async handler($){let Z=l("generate",$);if($.force==="true"||$.force===!0)Z.flags.force=!0;let Q=await x("generate");return R(Q,Z)}},{name:"midnight_info",description:"Display wallet address, network, creation date (no secrets shown)",inputSchema:{type:"object",properties:{wallet:{type:"string",description:"Custom wallet file path"}}},async handler($){let Z=l("info",$),Q=await x("info");return R(Q,Z)}},{name:"midnight_balance",description:"Check unshielded balance via indexer subscription",inputSchema:{type:"object",properties:{address:{type:"string",description:"Address to check (or reads from wallet file)"},wallet:{type:"string",description:"Custom wallet file path"},network:{type:"string",description:"Override network detection",enum:["preprod","preview","undeployed"]},"indexer-ws":{type:"string",description:"Custom indexer WebSocket URL"}}},async handler($){let Z=$.address,Q=l("balance",$,Z);delete Q.flags.address;let X=await x("balance");return R(X,Q)}},{name:"midnight_address",description:"Derive and display an unshielded address from a seed",inputSchema:{type:"object",properties:{seed:{type:"string",description:"Seed to derive from (required, 64-char hex)"},network:{type:"string",description:"Network for address prefix",enum:["preprod","preview","undeployed"]},index:{type:"string",description:"Key derivation index (default: 0)"}},required:["seed"]},async handler($){let Z=l("address",$),Q=await x("address");return R(Q,Z)}},{name:"midnight_genesis_address",description:"Display the genesis wallet address (seed 0x01) for a network",inputSchema:{type:"object",properties:{network:{type:"string",description:"Network for address prefix",enum:["preprod","preview","undeployed"]}}},async handler($){let Z=l("genesis-address",$),Q=await x("genesis-address");return R(Q,Z)}},{name:"midnight_inspect_cost",description:"Display current block limits derived from LedgerParameters",inputSchema:{type:"object",properties:{}},async handler(){let $=l("inspect-cost",{}),Z=await x("inspect-cost");return R(Z,$)}},{name:"midnight_airdrop",description:"Fund your wallet from the genesis wallet (undeployed network only)",inputSchema:{type:"object",properties:{amount:{type:"string",description:"Amount in NIGHT to airdrop"},wallet:{type:"string",description:"Custom wallet file path"}},required:["amount"]},async handler($){let Z=$.amount,Q=l("airdrop",$,Z);delete Q.flags.amount;let X=await x("airdrop");return R(X,Q)}},{name:"midnight_transfer",description:"Send NIGHT tokens to another address",inputSchema:{type:"object",properties:{to:{type:"string",description:"Recipient bech32m address"},amount:{type:"string",description:"Amount in NIGHT to send"},wallet:{type:"string",description:"Custom wallet file path"}},required:["to","amount"]},async handler($){let{to:Z,amount:Q}=$,X=l("transfer",$,Z);X.positionals=[Q],delete X.flags.to,delete X.flags.amount;let q=await x("transfer");return R(q,X)}},{name:"midnight_dust_register",description:"Register NIGHT UTXOs for dust (fee token) generation",inputSchema:{type:"object",properties:{wallet:{type:"string",description:"Custom wallet file path"}}},async handler($){let Z=l("dust",$,"register"),Q=await x("dust");return R(Q,Z)}},{name:"midnight_dust_status",description:"Check dust registration status and balance",inputSchema:{type:"object",properties:{wallet:{type:"string",description:"Custom wallet file path"}}},async handler($){let Z=l("dust",$,"status"),Q=await x("dust");return R(Q,Z)}},{name:"midnight_config_get",description:"Read a persistent config value",inputSchema:{type:"object",properties:{key:{type:"string",description:'Config key to read (e.g. "network")'}},required:["key"]},async handler($){let Q={command:"config",subcommand:"get",positionals:[$.key],flags:{json:!0}},X=await x("config");return R(X,Q)}},{name:"midnight_config_set",description:"Write a persistent config value",inputSchema:{type:"object",properties:{key:{type:"string",description:'Config key to set (e.g. "network")'},value:{type:"string",description:"Config value to set"}},required:["key","value"]},async handler($){let{key:Z,value:Q}=$,X={command:"config",subcommand:"set",positionals:[Z,Q],flags:{json:!0}},q=await x("config");return R(q,X)}},{name:"midnight_localnet_up",description:"Start a local Midnight network via Docker Compose",inputSchema:{type:"object",properties:{}},async handler(){let $={command:"localnet",subcommand:"up",positionals:[],flags:{json:!0}},Z=await x("localnet");return R(Z,$)}},{name:"midnight_localnet_stop",description:"Stop local network containers (preserves state for fast restart)",inputSchema:{type:"object",properties:{}},async handler(){let $={command:"localnet",subcommand:"stop",positionals:[],flags:{json:!0}},Z=await x("localnet");return R(Z,$)}},{name:"midnight_localnet_down",description:"Remove local network containers, networks, and volumes (full teardown)",inputSchema:{type:"object",properties:{}},async handler(){let $={command:"localnet",subcommand:"down",positionals:[],flags:{json:!0}},Z=await x("localnet");return R(Z,$)}},{name:"midnight_localnet_status",description:"Show local network service status and ports",inputSchema:{type:"object",properties:{}},async handler(){let $={command:"localnet",subcommand:"status",positionals:[],flags:{json:!0}},Z=await x("localnet");return R(Z,$)}},{name:"midnight_localnet_clean",description:"Remove conflicting containers from other setups",inputSchema:{type:"object",properties:{}},async handler(){let $={command:"localnet",subcommand:"clean",positionals:[],flags:{json:!0}},Z=await x("localnet");return R(Z,$)}}],m1=new D$({name:"midnight-wallet-cli",version:q0},{capabilities:{tools:{}}});m1.setRequestHandler(x$,async()=>{return{tools:J2.map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}});m1.setRequestHandler(E$,async($)=>{let{name:Z,arguments:Q}=$.params,X=J2.find((q)=>q.name===Z);if(!X)return{content:[{type:"text",text:`Unknown tool: ${Z}`}],isError:!0};try{let q=await X.handler(Q??{});return{content:[{type:"text",text:JSON.stringify(q,null,2)}]}}catch(q){let z=q instanceof Error?q:new Error(String(q)),{errorCode:Y}=y0(z);return{content:[{type:"text",text:JSON.stringify({error:!0,code:Y,message:z.message})}],isError:!0}}});v$().catch(($)=>{process.stderr.write(`MCP server error: ${$.message}
276
+ `),process.exit(1)})});function U2($){let Z=Math.max(0,Math.min(1,$)),Q=H0[0].length,X=Math.floor(Z*Q);return H0.map((q)=>q.slice(0,X).padEnd(Q))}function B2($){let Z=Math.max(0,Math.min(1,$)),Q=Math.floor($*100);if(Z>=1)return H0;return H0.map((X,q)=>Array.from(X).map((z,Y)=>{if(z===" ")return" ";if(Z<=0)return r0(q+20,Y,0);let K=((q+20)*131+Y*997)%100/100;return Z>=K?z:r0(q+20,Y,Q)}).join(""))}function r0($,Z,Q){let X=($*131+Z*997+Q*7919)%65537/65537;return G2[Math.floor(X*G2.length)]}function V2($){let Z=Math.max(0,Math.min(1,$)),Q=t0.split(`
277
+ `),X=Math.floor($*100);if(Z>=1)return t0;if(Z<=0)return Q.map((q,z)=>Array.from(q).map((Y,K)=>r0(z,K,0)).join("")).join(`
278
+ `);return Q.map((q,z)=>Array.from(q).map((Y,K)=>{if(Y===" ")return" ";let G=(z*131+K*997)%100/100;return Z>=G?Y:r0(z,K,X)}).join("")).join(`
279
+ `)}var t0,H0,g1,G2;var d1=O(()=>{t0=[" ████████████ "," ███ ███ "," ███ ██ ███ "," ██ ██ "," ██ ██ ██ "," ██ ██ "," ██ ██ ██ "," ██ ██ "," ██ ██ "," ██ ██ "," ██ ██ "," ███ ███ "," ███ ███ "," ████████████ "].join(`
280
+ `),H0=["█▄ ▄█ █ █▀▄ █▄ █ █ █▀▀ █ █ ▀█▀","█ █ █ █ █ █ █ ██ █ █ █ █▀█ █ ","▀ ▀ ▀ ▀▀ ▀ ▀ ▀ ▀▀▀ ▀ ▀ ▀ "];g1=[["generate","Generate or restore a wallet"],["info","Display wallet metadata"],["balance","Check unshielded balance"],["address","Derive address from seed"],["genesis-address","Show genesis address"],["inspect-cost","Display block limits"],["airdrop","Fund from genesis wallet"],["transfer","Send NIGHT tokens"],["dust","Manage dust (fee tokens)"],["config","Manage CLI config"],["localnet","Manage local network"],["help","Show command usage"]],G2=["░","▒","▓","█","·"," "]});function i1($,Z){return new Promise((Q,X)=>{if(Z?.aborted){Q();return}let q=setTimeout(Q,$);Z?.addEventListener("abort",()=>{clearTimeout(q),Q()},{once:!0})})}async function W2($,Z){let X=t0.split(`
281
+ `),q=X.length,z=36,Y=Math.max(q,Z?.length??0),K=3;if(!i()){for(let B=0;B<Y;B++){let F=(B<q?X[B]:"").padEnd(35),M=Z?.[B]??"";process.stderr.write(F+M+`
282
+ `)}return}function G(B,F){for(let M=0;M<Y;M++){let _=M<B.length?F0(B[M]):"",T=F[M]??"";if(T)process.stderr.write(_+"\x1B[36G"+T+`\x1B[K
283
+ `);else process.stderr.write(_+`\x1B[K
284
+ `)}}function U(){process.stderr.write(`\x1B[${Y}A`)}for(let B=0;B<=20;B++){if($?.aborted)break;let F=B/20,_=V2(F).split(`
285
+ `);if(B>0)U();G(_,[]),await i1(l1,$)}let V=20;for(let B=0;B<=V;B++){if($?.aborted)break;let F=B/V,M=U2(F);U();let _=new Array(Y).fill(null);for(let T=0;T<M.length;T++)_[T]=y(F0(M[T]));G(X,_),await i1(l1,$)}let J=12;for(let B=0;B<=J;B++){if($?.aborted)break;let F=B/J,M=B2(F);U();let _=new Array(Y).fill(null);for(let T=0;T<M.length;T++)_[T]=y(F0(M[T]));G(X,_),await i1(l1,$)}U();let W=new Array(Y).fill(null);if(Z)for(let B=0;B<Z.length;B++)if(B<3)W[B]=y(F0(Z[B]));else W[B]=Z[B];G(X,W)}var l1=80;var H2=O(()=>{d1()});var F2={};S(F2,{default:()=>j2,COMMAND_SPECS:()=>A0});function b$(){let $=[];for(let Z of H0)$.push(Z);$.push(""),$.push(y("Commands"));for(let[Z,Q]of g1)$.push(`${t(Z.padEnd(18))}${Q}`);return $.push(""),$.push(j("midnight (or mn) help <command>")),$.push(j("--json flag available on all commands")),$.push(j("midnight help --agent")+j(" AI & MCP reference")),$}function w$(){process.stderr.write(`
3164
286
  Commands:
3165
287
 
3166
- `);
3167
- for (const [name, brief] of COMMAND_BRIEFS) {
3168
- process.stderr.write(` ${name.padEnd(18)}${brief}
3169
- `);
3170
- }
3171
- process.stderr.write(`
288
+ `);for(let[$,Z]of g1)process.stderr.write(` ${$.padEnd(18)}${Z}
289
+ `);process.stderr.write(`
3172
290
  Usage: midnight <command> (or: mn <command>)
3173
- `);
3174
- process.stderr.write(` --json flag available on all commands
3175
- `);
3176
- process.stderr.write(` midnight help --agent AI & MCP reference
3177
-
3178
- `);
3179
- }
3180
- function printCommandHelp(spec) {
3181
- process.stdout.write(`
3182
- ` + header(spec.name) + `
3183
-
3184
- `);
3185
- process.stdout.write(` ${spec.description}
3186
-
3187
- `);
3188
- process.stdout.write(gray("Usage:") + `
3189
- `);
3190
- process.stdout.write(` ${spec.usage}
3191
-
3192
- `);
3193
- if (spec.flags && spec.flags.length > 0) {
3194
- process.stdout.write(gray("Flags:") + `
3195
- `);
3196
- for (const flag of spec.flags) {
3197
- process.stdout.write(` ${flag}
3198
- `);
3199
- }
3200
- process.stdout.write(`
3201
- `);
3202
- }
3203
- if (spec.examples && spec.examples.length > 0) {
3204
- process.stdout.write(gray("Examples:") + `
3205
- `);
3206
- for (const example of spec.examples) {
3207
- process.stdout.write(` ${dim("$")} ${example}
3208
- `);
3209
- }
3210
- process.stdout.write(`
3211
- `);
3212
- }
3213
- }
3214
- function outputJsonManifest() {
3215
- const manifest = {
3216
- cli: {
3217
- name: PKG_NAME,
3218
- version: PKG_VERSION,
3219
- description: PKG_DESCRIPTION,
3220
- bin: ["midnight", "mn"]
3221
- },
3222
- globalFlags: [
3223
- { name: "--json", description: "Output structured JSON to stdout (suppresses all stderr)" },
3224
- { name: "--wallet <file>", description: "Custom wallet file path" },
3225
- { name: "--network <name>", description: "Override network (preprod, preview, undeployed)" },
3226
- { name: "--version, -v", description: "Print CLI version" },
3227
- { name: "--help, -h", description: "Show help" }
3228
- ],
3229
- commands: COMMAND_SPECS.map((spec) => ({
3230
- name: spec.name,
3231
- description: spec.description,
3232
- usage: spec.usage,
3233
- flags: spec.flags,
3234
- examples: spec.examples,
3235
- jsonFields: spec.jsonFields
3236
- }))
3237
- };
3238
- writeJsonResult(manifest);
3239
- }
3240
- function printAgentManual() {
3241
- const manual = `
291
+ `),process.stderr.write(` --json flag available on all commands
292
+ `),process.stderr.write(` midnight help --agent AI & MCP reference
293
+
294
+ `)}function S$($){if(process.stdout.write(`
295
+ `+I($.name)+`
296
+
297
+ `),process.stdout.write(` ${$.description}
298
+
299
+ `),process.stdout.write(G0("Usage:")+`
300
+ `),process.stdout.write(` ${$.usage}
301
+
302
+ `),$.flags&&$.flags.length>0){process.stdout.write(G0("Flags:")+`
303
+ `);for(let Z of $.flags)process.stdout.write(` ${Z}
304
+ `);process.stdout.write(`
305
+ `)}if($.examples&&$.examples.length>0){process.stdout.write(G0("Examples:")+`
306
+ `);for(let Z of $.examples)process.stdout.write(` ${j("$")} ${Z}
307
+ `);process.stdout.write(`
308
+ `)}}function C$(){let $={cli:{name:V3,version:q0,description:W3,bin:["midnight","mn"]},globalFlags:[{name:"--json",description:"Output structured JSON to stdout (suppresses all stderr)"},{name:"--wallet <file>",description:"Custom wallet file path"},{name:"--network <name>",description:"Override network (preprod, preview, undeployed)"},{name:"--version, -v",description:"Print CLI version"},{name:"--help, -h",description:"Show help"}],commands:A0.map((Z)=>({name:Z.name,description:Z.description,usage:Z.usage,flags:Z.flags,examples:Z.examples,jsonFields:Z.jsonFields}))};L($)}function f$(){let $=`
3242
309
  MIDNIGHT CLI — AI Agent & MCP Reference
3243
310
  ========================================
3244
311
 
3245
- Version: ${PKG_VERSION}
312
+ Version: ${q0}
3246
313
 
3247
314
  STRUCTURED JSON OUTPUT
3248
315
  ──────────────────────
@@ -3265,15 +332,12 @@ for programmatic discovery of CLI capabilities.
3265
332
 
3266
333
  COMMANDS & JSON SCHEMAS
3267
334
  ───────────────────────
3268
- ${COMMAND_SPECS.filter((s) => s.jsonFields).map((spec) => {
3269
- const fields = Object.entries(spec.jsonFields).map(([k, v]) => ` ${k.padEnd(20)}${v}`).join(`
3270
- `);
3271
- return `
3272
- ${spec.name}
3273
- ${spec.usage}
335
+ ${A0.filter((Z)=>Z.jsonFields).map((Z)=>{let Q=Object.entries(Z.jsonFields).map(([X,q])=>` ${X.padEnd(20)}${q}`).join(`
336
+ `);return`
337
+ ${Z.name}
338
+ ${Z.usage}
3274
339
  JSON fields:
3275
- ${fields}`;
3276
- }).join(`
340
+ ${Q}`}).join(`
3277
341
  `)}
3278
342
 
3279
343
  ERROR CODES
@@ -3347,384 +411,10 @@ EXAMPLE WORKFLOW
3347
411
  # 4. Transfer tokens
3348
412
  midnight transfer mn_addr_... 100 --json
3349
413
  # → {"txHash":"...","amount":"100","recipient":"mn_addr_...","network":"undeployed"}
3350
- `;
3351
- process.stdout.write(manual);
3352
- }
3353
- async function helpCommand(args) {
3354
- if (hasFlag(args, "agent")) {
3355
- printAgentManual();
3356
- return;
3357
- }
3358
- if (hasFlag(args, "json")) {
3359
- outputJsonManifest();
3360
- return;
3361
- }
3362
- const targetCommand = args.subcommand;
3363
- if (targetCommand) {
3364
- const spec = COMMAND_SPECS.find((s) => s.name === targetCommand);
3365
- if (!spec) {
3366
- throw new Error(`Unknown command: "${targetCommand}"
3367
- ` + `Available commands: ${COMMAND_SPECS.map((s) => s.name).join(", ")}`);
3368
- }
3369
- printCommandHelp(spec);
3370
- return;
3371
- }
3372
- if (!process.stderr.isTTY) {
3373
- printPlainHelp();
3374
- return;
3375
- }
3376
- const rightColumn = buildRightColumn();
3377
- await animateMaterialize(undefined, rightColumn);
3378
- }
3379
- var COMMAND_SPECS;
3380
- var init_help = __esm(() => {
3381
- init_format();
3382
- init_animate();
3383
- init_art();
3384
- init_pkg();
3385
- COMMAND_SPECS = [
3386
- {
3387
- name: "generate",
3388
- description: "Generate a new wallet (random mnemonic, or restore from seed/mnemonic)",
3389
- usage: 'midnight generate [--network <name>] [--seed <hex>] [--mnemonic "..."] [--output <file>] [--force]',
3390
- flags: [
3391
- "--network <name> Network: preprod, preview, undeployed",
3392
- "--seed <hex> Restore from existing seed (64-char hex)",
3393
- '--mnemonic "..." Restore from BIP-39 mnemonic (24 words)',
3394
- "--output <file> Custom output path (default: ~/.midnight/wallet.json)",
3395
- "--force Overwrite existing wallet file"
3396
- ],
3397
- examples: [
3398
- "midnight generate --network preprod",
3399
- "midnight generate --network preprod --output my-wallet.json",
3400
- "midnight generate --seed 0123456789abcdef..."
3401
- ],
3402
- jsonFields: {
3403
- address: "Generated wallet address (bech32m)",
3404
- network: "Network name",
3405
- seed: "Hex-encoded 32-byte seed",
3406
- mnemonic: "BIP-39 mnemonic (24 words, only if generated or provided)",
3407
- file: "Path where wallet file was saved",
3408
- createdAt: "ISO 8601 creation timestamp"
3409
- }
3410
- },
3411
- {
3412
- name: "info",
3413
- description: "Display wallet address, network, creation date (no secrets shown)",
3414
- usage: "midnight info [--wallet <file>]",
3415
- flags: [
3416
- "--wallet <file> Custom wallet file path"
3417
- ],
3418
- examples: [
3419
- "midnight info",
3420
- "midnight info --wallet my-wallet.json"
3421
- ],
3422
- jsonFields: {
3423
- address: "Wallet address (bech32m)",
3424
- network: "Network name",
3425
- createdAt: "ISO 8601 creation timestamp",
3426
- file: "Wallet file path"
3427
- }
3428
- },
3429
- {
3430
- name: "balance",
3431
- description: "Check unshielded balance via GraphQL subscription",
3432
- usage: "midnight balance [address] [--network <name>] [--indexer-ws <url>]",
3433
- flags: [
3434
- "<address> Address to check (or reads from wallet file)",
3435
- "--network <name> Override network detection",
3436
- "--indexer-ws <url> Custom indexer WebSocket URL"
3437
- ],
3438
- examples: [
3439
- "midnight balance",
3440
- "midnight balance mn_addr_preprod1...",
3441
- "midnight balance --network preprod"
3442
- ],
3443
- jsonFields: {
3444
- address: "Checked address (bech32m)",
3445
- network: "Network name",
3446
- balances: "Object mapping token type to balance string",
3447
- utxoCount: "Number of UTXOs",
3448
- txCount: "Number of transactions synced"
3449
- }
3450
- },
3451
- {
3452
- name: "address",
3453
- description: "Derive and display an unshielded address from a seed",
3454
- usage: "midnight address --seed <hex> [--network <name>] [--index <n>]",
3455
- flags: [
3456
- "--seed <hex> Seed to derive from (required, 64-char hex)",
3457
- "--network <name> Network for address prefix (default: resolved)",
3458
- "--index <n> Key derivation index (default: 0)"
3459
- ],
3460
- examples: [
3461
- "midnight address --seed 0123456789abcdef... --network preprod",
3462
- "midnight address --seed 0123456789abcdef... --index 1"
3463
- ],
3464
- jsonFields: {
3465
- address: "Derived address (bech32m)",
3466
- network: "Network name",
3467
- index: "Key derivation index",
3468
- path: "BIP-44 derivation path"
3469
- }
3470
- },
3471
- {
3472
- name: "genesis-address",
3473
- description: "Display the genesis wallet address (seed 0x01) for a network",
3474
- usage: "midnight genesis-address [--network <name>]",
3475
- flags: [
3476
- "--network <name> Network for address prefix (default: resolved)"
3477
- ],
3478
- examples: [
3479
- "midnight genesis-address --network undeployed",
3480
- "midnight genesis-address --network preprod"
3481
- ],
3482
- jsonFields: {
3483
- address: "Genesis wallet address (bech32m)",
3484
- network: "Network name"
3485
- }
3486
- },
3487
- {
3488
- name: "inspect-cost",
3489
- description: "Display current block limits derived from LedgerParameters",
3490
- usage: "midnight inspect-cost",
3491
- examples: [
3492
- "midnight inspect-cost"
3493
- ],
3494
- jsonFields: {
3495
- readTime: "Read time limit (picoseconds)",
3496
- computeTime: "Compute time limit (picoseconds)",
3497
- blockUsage: "Block usage limit (bytes)",
3498
- bytesWritten: "Bytes written limit (bytes)",
3499
- bytesChurned: "Bytes churned limit (bytes)"
3500
- }
3501
- },
3502
- {
3503
- name: "airdrop",
3504
- description: "Fund your wallet from the genesis wallet (undeployed network only)",
3505
- usage: "midnight airdrop <amount> [--wallet <file>]",
3506
- flags: [
3507
- "<amount> Amount in NIGHT to airdrop",
3508
- "--wallet <file> Custom wallet file path"
3509
- ],
3510
- examples: [
3511
- "midnight airdrop 1000",
3512
- "midnight airdrop 0.5 --wallet my-wallet.json"
3513
- ],
3514
- jsonFields: {
3515
- txHash: "Transaction hash",
3516
- amount: "Amount airdropped (NIGHT string)",
3517
- recipient: "Recipient address (bech32m)",
3518
- network: "Network name"
3519
- }
3520
- },
3521
- {
3522
- name: "transfer",
3523
- description: "Send NIGHT tokens to another address",
3524
- usage: "midnight transfer <to> <amount> [--wallet <file>]",
3525
- flags: [
3526
- "<to> Recipient bech32m address",
3527
- "<amount> Amount in NIGHT to send",
3528
- "--wallet <file> Custom wallet file path"
3529
- ],
3530
- examples: [
3531
- "midnight transfer mn_addr_undeployed1... 100",
3532
- "midnight transfer mn_addr_preprod1... 50 --wallet my-wallet.json"
3533
- ],
3534
- jsonFields: {
3535
- txHash: "Transaction hash",
3536
- amount: "Amount transferred (NIGHT string)",
3537
- recipient: "Recipient address (bech32m)",
3538
- network: "Network name"
3539
- }
3540
- },
3541
- {
3542
- name: "dust",
3543
- description: "Register UTXOs for dust (fee token) generation or check status",
3544
- usage: "midnight dust <register|status> [--wallet <file>]",
3545
- flags: [
3546
- "register Register NIGHT UTXOs for dust generation",
3547
- "status Check dust registration status and balance",
3548
- "--wallet <file> Custom wallet file path"
3549
- ],
3550
- examples: [
3551
- "midnight dust register",
3552
- "midnight dust status"
3553
- ],
3554
- jsonFields: {
3555
- subcommand: "register or status",
3556
- dustBalance: "Dust balance (raw bigint string)",
3557
- registered: "Number of registered UTXOs (status only)",
3558
- unregistered: "Number of unregistered UTXOs (status only)",
3559
- nightBalance: "NIGHT balance (raw bigint string, status only)",
3560
- dustAvailable: "Whether dust tokens are available (status only)",
3561
- txHash: "Registration transaction hash (register only, if submitted)"
3562
- }
3563
- },
3564
- {
3565
- name: "config",
3566
- description: "Manage persistent config (default network, etc.)",
3567
- usage: "midnight config <get|set> <key> [value]",
3568
- flags: [
3569
- "get <key> Read a config value",
3570
- "set <key> <value> Write a config value"
3571
- ],
3572
- examples: [
3573
- "midnight config get network",
3574
- "midnight config set network preprod"
3575
- ],
3576
- jsonFields: {
3577
- action: "get or set",
3578
- key: "Config key name",
3579
- value: "Config value"
3580
- }
3581
- },
3582
- {
3583
- name: "localnet",
3584
- description: "Manage a local Midnight network via Docker Compose",
3585
- usage: "midnight localnet <up|stop|down|status|logs|clean>",
3586
- flags: [
3587
- "up Start the local network (node, indexer, proof server)",
3588
- "stop Stop containers (preserves state for fast restart)",
3589
- "down Remove containers, networks, and volumes (full teardown)",
3590
- "status Show service status and ports",
3591
- "logs Stream service logs (Ctrl+C to stop)",
3592
- "clean Remove conflicting containers from other setups"
3593
- ],
3594
- examples: [
3595
- "midnight localnet up",
3596
- "midnight localnet stop",
3597
- "midnight localnet status",
3598
- "midnight localnet down",
3599
- "midnight localnet clean"
3600
- ],
3601
- jsonFields: {
3602
- subcommand: "up, stop, down, status, or clean",
3603
- services: "Array of { name, state, port, health? } (up/status only)",
3604
- status: "Operation result message (stop/down/clean)",
3605
- removed: "Array of removed container names (clean only)"
3606
- }
3607
- },
3608
- {
3609
- name: "help",
3610
- description: "Show usage for all commands or a specific command",
3611
- usage: "midnight help [command]",
3612
- examples: [
3613
- "midnight help",
3614
- "midnight help balance"
3615
- ],
3616
- jsonFields: {
3617
- cli: "CLI metadata (name, version, description)",
3618
- globalFlags: "Array of global flag descriptions",
3619
- commands: "Array of command specs with jsonFields"
3620
- }
3621
- }
3622
- ];
3623
- });
3624
-
3625
- // src/wallet.ts
3626
- init_format();
3627
- init_exit_codes();
3628
- init_pkg();
3629
- if (process.argv.includes("--mcp")) {
3630
- await Promise.resolve().then(() => (init_mcp_server(), exports_mcp_server));
3631
- } else {
3632
- let handleShutdown = function() {
3633
- abortController.abort();
3634
- setTimeout(() => process.exit(130), 5000).unref();
3635
- };
3636
- const args = parseArgs();
3637
- const jsonMode = hasFlag(args, "json");
3638
- if (hasFlag(args, "version") || hasFlag(args, "v")) {
3639
- process.stdout.write(PKG_VERSION + `
3640
- `);
3641
- process.exit(0);
3642
- }
3643
- if (hasFlag(args, "help") || hasFlag(args, "h")) {
3644
- args.command = "help";
3645
- }
3646
- const command = args.command ?? "help";
3647
- let restoreStderr;
3648
- if (jsonMode) {
3649
- restoreStderr = suppressStderr();
3650
- }
3651
- const abortController = new AbortController;
3652
- const { signal } = abortController;
3653
- process.on("SIGINT", handleShutdown);
3654
- process.on("SIGTERM", handleShutdown);
3655
- async function run() {
3656
- switch (command) {
3657
- case "help": {
3658
- const { default: handler } = await Promise.resolve().then(() => (init_help(), exports_help));
3659
- return handler(args);
3660
- }
3661
- case "generate": {
3662
- const { default: handler } = await Promise.resolve().then(() => (init_generate(), exports_generate));
3663
- return handler(args);
3664
- }
3665
- case "info": {
3666
- const { default: handler } = await Promise.resolve().then(() => (init_info(), exports_info));
3667
- return handler(args);
3668
- }
3669
- case "balance": {
3670
- const { default: handler } = await Promise.resolve().then(() => (init_balance(), exports_balance));
3671
- return handler(args);
3672
- }
3673
- case "address": {
3674
- const { default: handler } = await Promise.resolve().then(() => (init_address(), exports_address));
3675
- return handler(args);
3676
- }
3677
- case "genesis-address": {
3678
- const { default: handler } = await Promise.resolve().then(() => (init_genesis_address(), exports_genesis_address));
3679
- return handler(args);
3680
- }
3681
- case "inspect-cost": {
3682
- const { default: handler } = await Promise.resolve().then(() => (init_inspect_cost(), exports_inspect_cost));
3683
- return handler(args);
3684
- }
3685
- case "config": {
3686
- const { default: handler } = await Promise.resolve().then(() => (init_config(), exports_config));
3687
- return handler(args);
3688
- }
3689
- case "airdrop": {
3690
- const { default: handler } = await Promise.resolve().then(() => (init_airdrop(), exports_airdrop));
3691
- return handler(args, signal);
3692
- }
3693
- case "transfer": {
3694
- const { default: handler } = await Promise.resolve().then(() => (init_transfer2(), exports_transfer));
3695
- return handler(args, signal);
3696
- }
3697
- case "dust": {
3698
- const { default: handler } = await Promise.resolve().then(() => (init_dust(), exports_dust));
3699
- return handler(args, signal);
3700
- }
3701
- case "localnet": {
3702
- const { default: handler } = await Promise.resolve().then(() => (init_localnet2(), exports_localnet));
3703
- return handler(args);
3704
- }
3705
- default:
3706
- throw new Error(`Unknown command: "${command}"
3707
- Run "midnight help" to see available commands.`);
3708
- }
3709
- }
3710
- const FACADE_COMMANDS = new Set(["airdrop", "transfer", "dust"]);
3711
- run().then(() => {
3712
- if (FACADE_COMMANDS.has(command)) {
3713
- process.exit(0);
3714
- }
3715
- }).catch((err) => {
3716
- if (jsonMode) {
3717
- restoreStderr?.();
3718
- const { exitCode, errorCode } = classifyError(err);
3719
- writeJsonError(err, errorCode, exitCode);
3720
- process.exit(exitCode);
3721
- } else {
3722
- process.stderr.write(`
3723
- ` + errorBox(err.message, 'Run "midnight help" for usage information.') + `
3724
-
3725
- `);
3726
- const { exitCode } = classifyError(err);
3727
- process.exit(exitCode);
3728
- }
3729
- });
3730
- }
414
+ `;process.stdout.write($)}async function j2($){if(P($,"agent")){f$();return}if(P($,"json")){C$();return}let Z=$.subcommand;if(Z){let X=A0.find((q)=>q.name===Z);if(!X)throw new Error(`Unknown command: "${Z}"
415
+ Available commands: ${A0.map((q)=>q.name).join(", ")}`);S$(X);return}if(!process.stderr.isTTY){w$();return}let Q=b$();await W2(void 0,Q)}var A0;var P2=O(()=>{N();H2();d1();w0();A0=[{name:"generate",description:"Generate a new wallet (random mnemonic, or restore from seed/mnemonic)",usage:'midnight generate [--network <name>] [--seed <hex>] [--mnemonic "..."] [--output <file>] [--force]',flags:["--network <name> Network: preprod, preview, undeployed","--seed <hex> Restore from existing seed (64-char hex)",'--mnemonic "..." Restore from BIP-39 mnemonic (24 words)',"--output <file> Custom output path (default: ~/.midnight/wallet.json)","--force Overwrite existing wallet file"],examples:["midnight generate --network preprod","midnight generate --network preprod --output my-wallet.json","midnight generate --seed 0123456789abcdef..."],jsonFields:{address:"Generated wallet address (bech32m)",network:"Network name",seed:"Hex-encoded 32-byte seed",mnemonic:"BIP-39 mnemonic (24 words, only if generated or provided)",file:"Path where wallet file was saved",createdAt:"ISO 8601 creation timestamp"}},{name:"info",description:"Display wallet address, network, creation date (no secrets shown)",usage:"midnight info [--wallet <file>]",flags:["--wallet <file> Custom wallet file path"],examples:["midnight info","midnight info --wallet my-wallet.json"],jsonFields:{address:"Wallet address (bech32m)",network:"Network name",createdAt:"ISO 8601 creation timestamp",file:"Wallet file path"}},{name:"balance",description:"Check unshielded balance via GraphQL subscription",usage:"midnight balance [address] [--network <name>] [--indexer-ws <url>]",flags:["<address> Address to check (or reads from wallet file)","--network <name> Override network detection","--indexer-ws <url> Custom indexer WebSocket URL"],examples:["midnight balance","midnight balance mn_addr_preprod1...","midnight balance --network preprod"],jsonFields:{address:"Checked address (bech32m)",network:"Network name",balances:"Object mapping token type to balance string",utxoCount:"Number of UTXOs",txCount:"Number of transactions synced"}},{name:"address",description:"Derive and display an unshielded address from a seed",usage:"midnight address --seed <hex> [--network <name>] [--index <n>]",flags:["--seed <hex> Seed to derive from (required, 64-char hex)","--network <name> Network for address prefix (default: resolved)","--index <n> Key derivation index (default: 0)"],examples:["midnight address --seed 0123456789abcdef... --network preprod","midnight address --seed 0123456789abcdef... --index 1"],jsonFields:{address:"Derived address (bech32m)",network:"Network name",index:"Key derivation index",path:"BIP-44 derivation path"}},{name:"genesis-address",description:"Display the genesis wallet address (seed 0x01) for a network",usage:"midnight genesis-address [--network <name>]",flags:["--network <name> Network for address prefix (default: resolved)"],examples:["midnight genesis-address --network undeployed","midnight genesis-address --network preprod"],jsonFields:{address:"Genesis wallet address (bech32m)",network:"Network name"}},{name:"inspect-cost",description:"Display current block limits derived from LedgerParameters",usage:"midnight inspect-cost",examples:["midnight inspect-cost"],jsonFields:{readTime:"Read time limit (picoseconds)",computeTime:"Compute time limit (picoseconds)",blockUsage:"Block usage limit (bytes)",bytesWritten:"Bytes written limit (bytes)",bytesChurned:"Bytes churned limit (bytes)"}},{name:"airdrop",description:"Fund your wallet from the genesis wallet (undeployed network only)",usage:"midnight airdrop <amount> [--wallet <file>]",flags:["<amount> Amount in NIGHT to airdrop","--wallet <file> Custom wallet file path"],examples:["midnight airdrop 1000","midnight airdrop 0.5 --wallet my-wallet.json"],jsonFields:{txHash:"Transaction hash",amount:"Amount airdropped (NIGHT string)",recipient:"Recipient address (bech32m)",network:"Network name"}},{name:"transfer",description:"Send NIGHT tokens to another address",usage:"midnight transfer <to> <amount> [--wallet <file>]",flags:["<to> Recipient bech32m address","<amount> Amount in NIGHT to send","--wallet <file> Custom wallet file path"],examples:["midnight transfer mn_addr_undeployed1... 100","midnight transfer mn_addr_preprod1... 50 --wallet my-wallet.json"],jsonFields:{txHash:"Transaction hash",amount:"Amount transferred (NIGHT string)",recipient:"Recipient address (bech32m)",network:"Network name"}},{name:"dust",description:"Register UTXOs for dust (fee token) generation or check status",usage:"midnight dust <register|status> [--wallet <file>]",flags:["register Register NIGHT UTXOs for dust generation","status Check dust registration status and balance","--wallet <file> Custom wallet file path"],examples:["midnight dust register","midnight dust status"],jsonFields:{subcommand:"register or status",dustBalance:"Dust balance (raw bigint string)",registered:"Number of registered UTXOs (status only)",unregistered:"Number of unregistered UTXOs (status only)",nightBalance:"NIGHT balance (raw bigint string, status only)",dustAvailable:"Whether dust tokens are available (status only)",txHash:"Registration transaction hash (register only, if submitted)"}},{name:"config",description:"Manage persistent config (default network, etc.)",usage:"midnight config <get|set> <key> [value]",flags:["get <key> Read a config value","set <key> <value> Write a config value"],examples:["midnight config get network","midnight config set network preprod"],jsonFields:{action:"get or set",key:"Config key name",value:"Config value"}},{name:"localnet",description:"Manage a local Midnight network via Docker Compose",usage:"midnight localnet <up|stop|down|status|logs|clean>",flags:["up Start the local network (node, indexer, proof server)","stop Stop containers (preserves state for fast restart)","down Remove containers, networks, and volumes (full teardown)","status Show service status and ports","logs Stream service logs (Ctrl+C to stop)","clean Remove conflicting containers from other setups"],examples:["midnight localnet up","midnight localnet stop","midnight localnet status","midnight localnet down","midnight localnet clean"],jsonFields:{subcommand:"up, stop, down, status, or clean",services:"Array of { name, state, port, health? } (up/status only)",status:"Operation result message (stop/down/clean)",removed:"Array of removed container names (clean only)"}},{name:"help",description:"Show usage for all commands or a specific command",usage:"midnight help [command]",examples:["midnight help","midnight help balance"],jsonFields:{cli:"CLI metadata (name, version, description)",globalFlags:"Array of global flag descriptions",commands:"Array of command specs with jsonFields"}}]});N();Z1();w0();if(process.argv.includes("--mcp"))await Promise.resolve().then(() => (K2(),k$));else{let Y=function(){q.abort(),setTimeout(()=>process.exit(130),5000).unref()},$=o1(),Z=P($,"json");if(P($,"version")||P($,"v"))process.stdout.write(q0+`
416
+ `),process.exit(0);if(P($,"help")||P($,"h"))$.command="help";let Q=$.command??"help",X;if(Z)X=G3();let q=new AbortController,{signal:z}=q;process.on("SIGINT",Y),process.on("SIGTERM",Y);async function K(){switch(Q){case"help":{let{default:U}=await Promise.resolve().then(() => (P2(),F2));return U($)}case"generate":{let{default:U}=await Promise.resolve().then(() => (U1(),G1));return U($)}case"info":{let{default:U}=await Promise.resolve().then(() => (V1(),B1));return U($)}case"balance":{let{default:U}=await Promise.resolve().then(() => (H1(),W1));return U($)}case"address":{let{default:U}=await Promise.resolve().then(() => (F1(),j1));return U($)}case"genesis-address":{let{default:U}=await Promise.resolve().then(() => (O1(),P1));return U($)}case"inspect-cost":{let{default:U}=await Promise.resolve().then(() => (y1(),L1));return U($)}case"config":{let{default:U}=await Promise.resolve().then(() => (S1(),w1));return U($)}case"airdrop":{let{default:U}=await Promise.resolve().then(() => (E1(),x1));return U($,z)}case"transfer":{let{default:U}=await Promise.resolve().then(() => (v1(),N1));return U($,z)}case"dust":{let{default:U}=await Promise.resolve().then(() => (b1(),k1));return U($,z)}case"localnet":{let{default:U}=await Promise.resolve().then(() => (c1(),u1));return U($)}default:throw new Error(`Unknown command: "${Q}"
417
+ Run "midnight help" to see available commands.`)}}let G=new Set(["airdrop","transfer","dust"]);K().then(()=>{if(G.has(Q))process.exit(0)}).catch((U)=>{if(Z){X?.();let{exitCode:V,errorCode:J}=y0(U);U3(U,J,V),process.exit(V)}else{process.stderr.write(`
418
+ `+K3(U.message,'Run "midnight help" for usage information.')+`
419
+
420
+ `);let{exitCode:V}=y0(U);process.exit(V)}})}