midnight-wallet-cli 0.1.0

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.
@@ -0,0 +1,2693 @@
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/json-output.ts
15
+ function setCaptureTarget(fn) {
16
+ captureTarget = fn;
17
+ }
18
+ function writeJsonResult(data) {
19
+ const json = JSON.stringify(data) + `
20
+ `;
21
+ if (captureTarget) {
22
+ captureTarget(json);
23
+ } else {
24
+ process.stdout.write(json);
25
+ }
26
+ }
27
+ var captureTarget = null;
28
+
29
+ // src/lib/argv.ts
30
+ function getFlag(args, name) {
31
+ const value = args.flags[name];
32
+ if (value === undefined || value === true)
33
+ return;
34
+ return value;
35
+ }
36
+ function hasFlag(args, name) {
37
+ return name in args.flags;
38
+ }
39
+ function requireFlag(args, name, description) {
40
+ const value = getFlag(args, name);
41
+ if (value === undefined) {
42
+ throw new Error(`Missing required flag: --${name} <${description}>`);
43
+ }
44
+ return value;
45
+ }
46
+
47
+ // src/lib/derive-address.ts
48
+ import { HDWallet, Roles } from "@midnight-ntwrk/wallet-sdk-hd";
49
+ import { createKeystore, PublicKey } from "@midnight-ntwrk/wallet-sdk-unshielded-wallet";
50
+ import { NetworkId } from "@midnight-ntwrk/wallet-sdk-abstractions";
51
+ function deriveUnshieldedAddress(seedBuffer, networkName, keyIndex = 0) {
52
+ const networkId = NETWORK_ID_MAP[networkName];
53
+ const hdResult = HDWallet.fromSeed(seedBuffer);
54
+ if (hdResult.type !== "seedOk") {
55
+ throw new Error("Invalid seed for HD wallet");
56
+ }
57
+ const derivation = hdResult.hdWallet.selectAccount(0).selectRole(Roles.NightExternal).deriveKeyAt(keyIndex);
58
+ if (derivation.type === "keyOutOfBounds") {
59
+ throw new Error(`Key index ${keyIndex} out of bounds`);
60
+ }
61
+ const keystore = createKeystore(derivation.key, networkId);
62
+ const publicKey = PublicKey.fromKeyStore(keystore);
63
+ return publicKey.address;
64
+ }
65
+ var NETWORK_ID_MAP;
66
+ var init_derive_address = __esm(() => {
67
+ NETWORK_ID_MAP = {
68
+ preprod: NetworkId.NetworkId.PreProd,
69
+ preview: NetworkId.NetworkId.Preview,
70
+ undeployed: NetworkId.NetworkId.Undeployed
71
+ };
72
+ });
73
+
74
+ // src/lib/network.ts
75
+ import { execSync } from "child_process";
76
+ function isValidNetworkName(name) {
77
+ return VALID_NETWORK_NAMES.includes(name);
78
+ }
79
+ function getNetworkConfig(name) {
80
+ return { ...NETWORK_CONFIGS[name] };
81
+ }
82
+ function getValidNetworkNames() {
83
+ return VALID_NETWORK_NAMES;
84
+ }
85
+ function detectNetworkFromAddress(address) {
86
+ if (address.startsWith("mn_addr_preprod1"))
87
+ return "preprod";
88
+ if (address.startsWith("mn_addr_preview1"))
89
+ return "preview";
90
+ if (address.startsWith("mn_addr_undeployed1"))
91
+ return "undeployed";
92
+ return null;
93
+ }
94
+ function detectTestcontainerPorts() {
95
+ try {
96
+ const output = execSync('docker ps --format "{{.Image}}|{{.Ports}}"', { encoding: "utf-8", timeout: 5000 });
97
+ const result = {};
98
+ for (const line of output.trim().split(`
99
+ `)) {
100
+ if (!line)
101
+ continue;
102
+ const [image, ports] = line.split("|");
103
+ const extractHostPort = (containerPort) => {
104
+ const regex = new RegExp(`0\\.0\\.0\\.0:(\\d+)->${containerPort}/tcp`);
105
+ const match = ports?.match(regex);
106
+ return match ? parseInt(match[1], 10) : undefined;
107
+ };
108
+ if (image.includes("indexer-standalone") || image.includes("indexer")) {
109
+ const port = extractHostPort(8088);
110
+ if (port)
111
+ result.indexerPort = port;
112
+ }
113
+ if (image.includes("midnight-node")) {
114
+ const port = extractHostPort(9944);
115
+ if (port)
116
+ result.nodePort = port;
117
+ }
118
+ if (image.includes("proof-server")) {
119
+ const port = extractHostPort(6300);
120
+ if (port)
121
+ result.proofServerPort = port;
122
+ }
123
+ }
124
+ return result;
125
+ } catch {
126
+ return {};
127
+ }
128
+ }
129
+ function resolveNetworkConfig(name) {
130
+ const config = getNetworkConfig(name);
131
+ if (name === "undeployed") {
132
+ const detected = detectTestcontainerPorts();
133
+ if (detected.indexerPort) {
134
+ config.indexer = `http://localhost:${detected.indexerPort}/api/v3/graphql`;
135
+ config.indexerWS = `ws://localhost:${detected.indexerPort}/api/v3/graphql/ws`;
136
+ }
137
+ if (detected.nodePort) {
138
+ config.node = `ws://localhost:${detected.nodePort}`;
139
+ }
140
+ if (detected.proofServerPort) {
141
+ config.proofServer = `http://localhost:${detected.proofServerPort}`;
142
+ }
143
+ }
144
+ return config;
145
+ }
146
+ var NETWORK_CONFIGS, VALID_NETWORK_NAMES;
147
+ var init_network = __esm(() => {
148
+ NETWORK_CONFIGS = {
149
+ preprod: {
150
+ indexer: "https://indexer.preprod.midnight.network/api/v3/graphql",
151
+ indexerWS: "wss://indexer.preprod.midnight.network/api/v3/graphql/ws",
152
+ node: "wss://rpc.preprod.midnight.network",
153
+ proofServer: "http://localhost:6300",
154
+ networkId: "PreProd"
155
+ },
156
+ preview: {
157
+ indexer: "https://indexer.preview.midnight.network/api/v3/graphql",
158
+ indexerWS: "wss://indexer.preview.midnight.network/api/v3/graphql/ws",
159
+ node: "wss://rpc.preview.midnight.network",
160
+ proofServer: "http://localhost:6300",
161
+ networkId: "Preview"
162
+ },
163
+ undeployed: {
164
+ indexer: "http://localhost:8088/api/v3/graphql",
165
+ indexerWS: "ws://localhost:8088/api/v3/graphql/ws",
166
+ node: "ws://localhost:9944",
167
+ proofServer: "http://localhost:6300",
168
+ networkId: "Undeployed"
169
+ }
170
+ };
171
+ VALID_NETWORK_NAMES = ["preprod", "preview", "undeployed"];
172
+ });
173
+
174
+ // src/lib/constants.ts
175
+ 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, 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";
176
+
177
+ // src/lib/cli-config.ts
178
+ import * as fs from "fs";
179
+ import * as path from "path";
180
+ import { homedir } from "os";
181
+ function getConfigDir(configDir) {
182
+ return configDir ?? path.join(homedir(), MIDNIGHT_DIR);
183
+ }
184
+ function getConfigPath(configDir) {
185
+ return path.join(getConfigDir(configDir), DEFAULT_CONFIG_FILENAME);
186
+ }
187
+ function ensureConfigDir(configDir) {
188
+ const dir = getConfigDir(configDir);
189
+ if (!fs.existsSync(dir)) {
190
+ fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE });
191
+ }
192
+ }
193
+ function loadCliConfig(configDir) {
194
+ const configPath = getConfigPath(configDir);
195
+ if (!fs.existsSync(configPath)) {
196
+ return { ...DEFAULT_CLI_CONFIG };
197
+ }
198
+ let content;
199
+ try {
200
+ content = fs.readFileSync(configPath, "utf-8");
201
+ } catch {
202
+ return { ...DEFAULT_CLI_CONFIG };
203
+ }
204
+ let parsed;
205
+ try {
206
+ parsed = JSON.parse(content);
207
+ } catch {
208
+ return { ...DEFAULT_CLI_CONFIG };
209
+ }
210
+ return {
211
+ network: parsed.network && isValidNetworkName(parsed.network) ? parsed.network : DEFAULT_CLI_CONFIG.network
212
+ };
213
+ }
214
+ function saveCliConfig(config, configDir) {
215
+ ensureConfigDir(configDir);
216
+ const configPath = getConfigPath(configDir);
217
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + `
218
+ `, { mode: FILE_MODE });
219
+ }
220
+ function getConfigValue(key, configDir) {
221
+ const config = loadCliConfig(configDir);
222
+ if (key === "network")
223
+ return config.network;
224
+ throw new Error(`Unknown config key: "${key}"
225
+ Valid keys: ${VALID_CONFIG_KEYS.join(", ")}`);
226
+ }
227
+ function setConfigValue(key, value, configDir) {
228
+ const config = loadCliConfig(configDir);
229
+ if (key === "network") {
230
+ if (!isValidNetworkName(value)) {
231
+ throw new Error(`Invalid network: "${value}"
232
+ Valid networks: preprod, preview, undeployed`);
233
+ }
234
+ config.network = value;
235
+ } else {
236
+ throw new Error(`Unknown config key: "${key}"
237
+ Valid keys: ${VALID_CONFIG_KEYS.join(", ")}`);
238
+ }
239
+ saveCliConfig(config, configDir);
240
+ }
241
+ function getValidConfigKeys() {
242
+ return VALID_CONFIG_KEYS;
243
+ }
244
+ var DEFAULT_CLI_CONFIG, VALID_CONFIG_KEYS;
245
+ var init_cli_config = __esm(() => {
246
+ init_network();
247
+ DEFAULT_CLI_CONFIG = {
248
+ network: "undeployed"
249
+ };
250
+ VALID_CONFIG_KEYS = ["network"];
251
+ });
252
+
253
+ // src/lib/resolve-network.ts
254
+ function resolveNetworkName(ctx) {
255
+ const flagValue = getFlag(ctx.args, "network");
256
+ if (flagValue !== undefined) {
257
+ if (!isValidNetworkName(flagValue)) {
258
+ throw new Error(`Invalid network: "${flagValue}"
259
+ ` + `Valid networks: ${getValidNetworkNames().join(", ")}`);
260
+ }
261
+ return flagValue;
262
+ }
263
+ if (ctx.walletNetwork && isValidNetworkName(ctx.walletNetwork)) {
264
+ return ctx.walletNetwork;
265
+ }
266
+ if (ctx.address) {
267
+ const detected = detectNetworkFromAddress(ctx.address);
268
+ if (detected)
269
+ return detected;
270
+ }
271
+ const cliConfig = loadCliConfig(ctx.configDir);
272
+ if (cliConfig.network && isValidNetworkName(cliConfig.network)) {
273
+ return cliConfig.network;
274
+ }
275
+ return "undeployed";
276
+ }
277
+ function resolveNetwork(ctx) {
278
+ const name = resolveNetworkName(ctx);
279
+ const config = resolveNetworkConfig(name);
280
+ return { name, config };
281
+ }
282
+ var init_resolve_network = __esm(() => {
283
+ init_network();
284
+ init_cli_config();
285
+ });
286
+
287
+ // src/lib/wallet-config.ts
288
+ import * as fs2 from "fs";
289
+ import * as path2 from "path";
290
+ import { homedir as homedir2 } from "os";
291
+ function getMidnightDir() {
292
+ return path2.join(homedir2(), MIDNIGHT_DIR);
293
+ }
294
+ function getDefaultWalletPath() {
295
+ return path2.join(getMidnightDir(), DEFAULT_WALLET_FILENAME);
296
+ }
297
+ function ensureMidnightDir() {
298
+ const dir = getMidnightDir();
299
+ if (!fs2.existsSync(dir)) {
300
+ fs2.mkdirSync(dir, { recursive: true, mode: DIR_MODE });
301
+ }
302
+ }
303
+ function loadWalletConfig(walletPath) {
304
+ const resolvedPath = walletPath ? path2.resolve(walletPath) : getDefaultWalletPath();
305
+ if (!fs2.existsSync(resolvedPath)) {
306
+ throw new Error(`Wallet file not found: ${resolvedPath}
307
+ ` + `Generate a wallet first: midnight generate --network <name>`);
308
+ }
309
+ let content;
310
+ try {
311
+ content = fs2.readFileSync(resolvedPath, "utf-8");
312
+ } catch (err) {
313
+ throw new Error(`Failed to read wallet file: ${resolvedPath}
314
+ ${err.message}`);
315
+ }
316
+ let config;
317
+ try {
318
+ config = JSON.parse(content);
319
+ } catch {
320
+ throw new Error(`Invalid JSON in wallet file: ${resolvedPath}`);
321
+ }
322
+ if (!config.seed || !config.network || !config.address || !config.createdAt) {
323
+ const missing = ["seed", "network", "address", "createdAt"].filter((f) => !config[f]);
324
+ throw new Error(`Wallet file is missing required fields (${missing.join(", ")}): ${resolvedPath}`);
325
+ }
326
+ if (!/^[0-9a-fA-F]+$/.test(config.seed)) {
327
+ throw new Error(`Invalid seed format in wallet file (expected hex string): ${resolvedPath}`);
328
+ }
329
+ if (!isValidNetworkName(config.network)) {
330
+ throw new Error(`Invalid network "${config.network}" in wallet file: ${resolvedPath}
331
+ ` + `Valid networks: preprod, preview, undeployed`);
332
+ }
333
+ return config;
334
+ }
335
+ function saveWalletConfig(config, walletPath) {
336
+ const resolvedPath = walletPath ? path2.resolve(walletPath) : getDefaultWalletPath();
337
+ if (!walletPath) {
338
+ ensureMidnightDir();
339
+ } else {
340
+ const dir = path2.dirname(resolvedPath);
341
+ if (!fs2.existsSync(dir)) {
342
+ fs2.mkdirSync(dir, { recursive: true, mode: DIR_MODE });
343
+ }
344
+ }
345
+ fs2.writeFileSync(resolvedPath, JSON.stringify(config, null, 2) + `
346
+ `, { mode: FILE_MODE });
347
+ return resolvedPath;
348
+ }
349
+ var init_wallet_config = __esm(() => {
350
+ init_network();
351
+ });
352
+
353
+ // src/ui/colors.ts
354
+ function isColorEnabled() {
355
+ return !("NO_COLOR" in process.env);
356
+ }
357
+ function fg(text, code) {
358
+ if (!isColorEnabled())
359
+ return text;
360
+ return `${ESC}38;5;${code}m${text}${RESET}`;
361
+ }
362
+ function bold(text) {
363
+ if (!isColorEnabled())
364
+ return text;
365
+ return `${ESC}1m${text}${RESET}`;
366
+ }
367
+ function dim(text) {
368
+ if (!isColorEnabled())
369
+ return text;
370
+ return `${ESC}2m${text}${RESET}`;
371
+ }
372
+ function teal(text) {
373
+ return fg(text, TEAL);
374
+ }
375
+ function red(text) {
376
+ return fg(text, RED_CODE);
377
+ }
378
+ function green(text) {
379
+ return fg(text, GREEN_CODE);
380
+ }
381
+ function yellow(text) {
382
+ return fg(text, YELLOW_CODE);
383
+ }
384
+ function gray(text) {
385
+ return fg(text, DIM_GRAY);
386
+ }
387
+ var ESC = "\x1B[", RESET = "\x1B[0m", TEAL = 38, DIM_GRAY = 245, RED_CODE = 196, GREEN_CODE = 40, YELLOW_CODE = 226;
388
+
389
+ // src/ui/format.ts
390
+ function header(title, width = DEFAULT_WIDTH) {
391
+ const paddedTitle = ` ${title} `;
392
+ const remaining = width - paddedTitle.length;
393
+ if (remaining <= 0)
394
+ return bold(paddedTitle);
395
+ const left = Math.floor(remaining / 2);
396
+ const right = remaining - left;
397
+ return bold("═".repeat(left) + paddedTitle + "═".repeat(right));
398
+ }
399
+ function divider(width = DEFAULT_WIDTH) {
400
+ return dim("─".repeat(width));
401
+ }
402
+ function keyValue(key, value, padWidth = 16) {
403
+ const paddedKey = (key + ":").padEnd(padWidth);
404
+ return ` ${gray(paddedKey)}${value}`;
405
+ }
406
+ function toNight(microNight) {
407
+ const isNegative = microNight < 0n;
408
+ const abs = isNegative ? -microNight : microNight;
409
+ const multiplier = BigInt(10 ** TOKEN_DECIMALS);
410
+ const whole = abs / multiplier;
411
+ const frac = abs % multiplier;
412
+ const fracStr = frac.toString().padStart(TOKEN_DECIMALS, "0");
413
+ const sign = isNegative ? "-" : "";
414
+ return `${sign}${whole}.${fracStr}`;
415
+ }
416
+ function formatNight(microNight) {
417
+ return `${toNight(microNight)} NIGHT`;
418
+ }
419
+ function toDust(specks) {
420
+ const isNegative = specks < 0n;
421
+ const abs = isNegative ? -specks : specks;
422
+ const multiplier = 10n ** BigInt(DUST_DECIMALS);
423
+ const whole = abs / multiplier;
424
+ const frac = abs % multiplier;
425
+ const fracStr = frac.toString().padStart(DUST_DECIMALS, "0");
426
+ const trimmed = fracStr.replace(/0+$/, "").padEnd(6, "0");
427
+ const sign = isNegative ? "-" : "";
428
+ return `${sign}${whole}.${trimmed}`;
429
+ }
430
+ function formatDust(specks) {
431
+ return `${toDust(specks)} DUST`;
432
+ }
433
+ function formatAddress(address, truncate = false) {
434
+ const display = truncate && address.length > 20 ? address.slice(0, 10) + "…" + address.slice(-8) : address;
435
+ return teal(display);
436
+ }
437
+ function successMessage(msg, txHash) {
438
+ const check = green("✓");
439
+ const parts = [`${check} ${msg}`];
440
+ if (txHash) {
441
+ parts.push(keyValue("Transaction", teal(txHash)));
442
+ }
443
+ return parts.join(`
444
+ `);
445
+ }
446
+ var DEFAULT_WIDTH = 60, DUST_DECIMALS = 15;
447
+ var init_format = () => {
448
+ };
449
+
450
+ // src/commands/generate.ts
451
+ var exports_generate = {};
452
+ __export(exports_generate, {
453
+ default: () => generateCommand
454
+ });
455
+ import * as fs3 from "fs";
456
+ import * as path3 from "path";
457
+ import { homedir as homedir3 } from "os";
458
+ import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from "@scure/bip39";
459
+ import { wordlist } from "@scure/bip39/wordlists/english.js";
460
+ async function generateCommand(args) {
461
+ const networkName = resolveNetworkName({ args });
462
+ const outputPath = getFlag(args, "output");
463
+ const seedHex = getFlag(args, "seed");
464
+ const mnemonicStr = getFlag(args, "mnemonic");
465
+ if (seedHex !== undefined && mnemonicStr !== undefined) {
466
+ throw new Error("Cannot specify both --seed and --mnemonic. Use one or the other.");
467
+ }
468
+ const targetPath = outputPath ? path3.resolve(outputPath) : path3.join(homedir3(), MIDNIGHT_DIR, DEFAULT_WALLET_FILENAME);
469
+ if (fs3.existsSync(targetPath) && !hasFlag(args, "force")) {
470
+ throw new Error(`Wallet file already exists: ${targetPath}
471
+ ` + `Use --force to overwrite, or --output <file> to save to a different path.`);
472
+ }
473
+ let seedBuffer;
474
+ let mnemonic;
475
+ if (seedHex !== undefined) {
476
+ const cleaned = seedHex.replace(/^0x/, "");
477
+ if (cleaned.length !== 64 || !/^[0-9a-fA-F]+$/.test(cleaned)) {
478
+ throw new Error("Seed must be a 64-character hex string (32 bytes)");
479
+ }
480
+ seedBuffer = Buffer.from(cleaned, "hex");
481
+ } else if (mnemonicStr !== undefined) {
482
+ if (!validateMnemonic(mnemonicStr, wordlist)) {
483
+ throw new Error("Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.");
484
+ }
485
+ mnemonic = mnemonicStr;
486
+ seedBuffer = Buffer.from(mnemonicToSeedSync(mnemonic).slice(0, 32));
487
+ } else {
488
+ mnemonic = generateMnemonic(wordlist, 256);
489
+ seedBuffer = Buffer.from(mnemonicToSeedSync(mnemonic).slice(0, 32));
490
+ }
491
+ const address = deriveUnshieldedAddress(seedBuffer, networkName);
492
+ const config = {
493
+ seed: seedBuffer.toString("hex"),
494
+ network: networkName,
495
+ address,
496
+ createdAt: new Date().toISOString()
497
+ };
498
+ if (mnemonic) {
499
+ config.mnemonic = mnemonic;
500
+ }
501
+ const savedPath = saveWalletConfig(config, outputPath);
502
+ if (hasFlag(args, "json")) {
503
+ const result = {
504
+ address,
505
+ network: networkName,
506
+ seed: seedBuffer.toString("hex"),
507
+ file: savedPath,
508
+ createdAt: config.createdAt
509
+ };
510
+ if (mnemonic)
511
+ result.mnemonic = mnemonic;
512
+ writeJsonResult(result);
513
+ return;
514
+ }
515
+ process.stdout.write(address + `
516
+ `);
517
+ process.stderr.write(`
518
+ ` + header("Wallet Generated") + `
519
+
520
+ `);
521
+ process.stderr.write(keyValue("Network", networkName) + `
522
+ `);
523
+ process.stderr.write(keyValue("Address", formatAddress(address)) + `
524
+ `);
525
+ process.stderr.write(keyValue("File", savedPath) + `
526
+ `);
527
+ process.stderr.write(`
528
+ `);
529
+ if (mnemonic) {
530
+ process.stderr.write(yellow(bold(" MNEMONIC (save securely!):")) + `
531
+ `);
532
+ process.stderr.write(` ${mnemonic}
533
+
534
+ `);
535
+ }
536
+ process.stderr.write(yellow(bold(" SEED (hex):")) + `
537
+ `);
538
+ process.stderr.write(` ${seedBuffer.toString("hex")}
539
+
540
+ `);
541
+ process.stderr.write(divider() + `
542
+ `);
543
+ process.stderr.write(dim(" Next: midnight info | midnight balance") + `
544
+
545
+ `);
546
+ process.stderr.write(green("✓") + ` Wallet saved
547
+ `);
548
+ }
549
+ var init_generate = __esm(() => {
550
+ init_derive_address();
551
+ init_resolve_network();
552
+ init_wallet_config();
553
+ init_format();
554
+ });
555
+
556
+ // src/commands/info.ts
557
+ var exports_info = {};
558
+ __export(exports_info, {
559
+ default: () => infoCommand
560
+ });
561
+ import * as path4 from "path";
562
+ import { homedir as homedir4 } from "os";
563
+ async function infoCommand(args) {
564
+ const walletPath = getFlag(args, "wallet");
565
+ const config = loadWalletConfig(walletPath);
566
+ const resolvedPath = walletPath ? path4.resolve(walletPath) : path4.join(homedir4(), MIDNIGHT_DIR, DEFAULT_WALLET_FILENAME);
567
+ if (hasFlag(args, "json")) {
568
+ writeJsonResult({
569
+ address: config.address,
570
+ network: config.network,
571
+ createdAt: config.createdAt,
572
+ file: resolvedPath
573
+ });
574
+ return;
575
+ }
576
+ process.stdout.write(config.address + `
577
+ `);
578
+ process.stderr.write(`
579
+ ` + header("Wallet Info") + `
580
+
581
+ `);
582
+ process.stderr.write(keyValue("Address", formatAddress(config.address)) + `
583
+ `);
584
+ process.stderr.write(keyValue("Network", config.network) + `
585
+ `);
586
+ process.stderr.write(keyValue("Created", config.createdAt) + `
587
+ `);
588
+ process.stderr.write(keyValue("File", resolvedPath) + `
589
+ `);
590
+ process.stderr.write(`
591
+ ` + divider() + `
592
+
593
+ `);
594
+ }
595
+ var init_info = __esm(() => {
596
+ init_wallet_config();
597
+ init_format();
598
+ init_format();
599
+ });
600
+
601
+ // src/lib/balance-subscription.ts
602
+ import WebSocket from "ws";
603
+ function checkBalance(address, indexerWS, onProgress) {
604
+ return new Promise((resolve4, reject) => {
605
+ const ws = new WebSocket(indexerWS, ["graphql-transport-ws"]);
606
+ const utxos = new Map;
607
+ let txCount = 0;
608
+ let highestTxId = 0;
609
+ let lastSeenTxId = 0;
610
+ let progressReceived = false;
611
+ let settled = false;
612
+ let timeoutId;
613
+ const buildResult = () => {
614
+ const balances = new Map;
615
+ let utxoCount = 0;
616
+ for (const utxo of utxos.values()) {
617
+ if (!utxo.spent) {
618
+ utxoCount++;
619
+ const current = balances.get(utxo.tokenType) ?? 0n;
620
+ balances.set(utxo.tokenType, current + utxo.value);
621
+ }
622
+ }
623
+ return { balances, utxoCount, txCount, highestTxId };
624
+ };
625
+ const settle = () => {
626
+ clearTimeout(timeoutId);
627
+ };
628
+ const checkComplete = () => {
629
+ if (!settled && progressReceived && (highestTxId === 0 || lastSeenTxId >= highestTxId)) {
630
+ settled = true;
631
+ settle();
632
+ ws.send(JSON.stringify({ id: "1", type: "complete" }));
633
+ ws.close();
634
+ resolve4(buildResult());
635
+ }
636
+ };
637
+ ws.on("open", () => {
638
+ ws.send(JSON.stringify({ type: "connection_init" }));
639
+ });
640
+ ws.on("message", (data) => {
641
+ const message = JSON.parse(data.toString());
642
+ switch (message.type) {
643
+ case "connection_ack":
644
+ ws.send(JSON.stringify({
645
+ id: "1",
646
+ type: "subscribe",
647
+ payload: {
648
+ query: SUBSCRIPTION_QUERY,
649
+ variables: { address }
650
+ }
651
+ }));
652
+ break;
653
+ case "next": {
654
+ if (message.payload?.errors) {
655
+ const errMsg = message.payload.errors[0]?.message || "Unknown GraphQL error";
656
+ if (!settled) {
657
+ settled = true;
658
+ settle();
659
+ ws.close();
660
+ reject(new Error(`GraphQL error: ${errMsg}`));
661
+ }
662
+ return;
663
+ }
664
+ const event = message.payload?.data?.unshieldedTransactions;
665
+ if (!event)
666
+ return;
667
+ if (event.__typename === "UnshieldedTransaction") {
668
+ txCount++;
669
+ const tx = event;
670
+ lastSeenTxId = Math.max(lastSeenTxId, tx.transaction.id);
671
+ for (const utxo of tx.createdUtxos) {
672
+ const key = `${utxo.intentHash}:${utxo.outputIndex}`;
673
+ utxos.set(key, {
674
+ value: BigInt(utxo.value),
675
+ tokenType: utxo.tokenType,
676
+ spent: false
677
+ });
678
+ }
679
+ for (const utxo of tx.spentUtxos) {
680
+ const key = `${utxo.intentHash}:${utxo.outputIndex}`;
681
+ const existing = utxos.get(key);
682
+ if (existing) {
683
+ existing.spent = true;
684
+ }
685
+ }
686
+ if (onProgress) {
687
+ onProgress(lastSeenTxId, highestTxId);
688
+ }
689
+ checkComplete();
690
+ } else if (event.__typename === "UnshieldedTransactionsProgress") {
691
+ const progress = event;
692
+ highestTxId = progress.highestTransactionId;
693
+ progressReceived = true;
694
+ checkComplete();
695
+ }
696
+ break;
697
+ }
698
+ case "error":
699
+ if (!settled) {
700
+ settled = true;
701
+ settle();
702
+ ws.close();
703
+ reject(new Error(`GraphQL subscription error: ${JSON.stringify(message.payload)}`));
704
+ }
705
+ break;
706
+ case "complete":
707
+ break;
708
+ }
709
+ });
710
+ ws.on("error", (error) => {
711
+ if (!settled) {
712
+ settled = true;
713
+ settle();
714
+ reject(new Error(`WebSocket connection failed: ${error.message}`));
715
+ }
716
+ });
717
+ ws.on("close", () => {
718
+ if (!settled) {
719
+ settled = true;
720
+ settle();
721
+ reject(new Error(`Indexer closed the connection before balance sync completed. ` + `Indexer: ${indexerWS}`));
722
+ }
723
+ });
724
+ timeoutId = setTimeout(() => {
725
+ if (!settled) {
726
+ settled = true;
727
+ ws.close();
728
+ reject(new Error(`Balance check timed out after ${BALANCE_CHECK_TIMEOUT_MS / 1000}s. ` + `Indexer: ${indexerWS}`));
729
+ }
730
+ }, BALANCE_CHECK_TIMEOUT_MS);
731
+ });
732
+ }
733
+ function isNativeToken(tokenType) {
734
+ return tokenType === NATIVE_TOKEN_TYPE;
735
+ }
736
+ var SUBSCRIPTION_QUERY = `
737
+ subscription UnshieldedTransactions($address: UnshieldedAddress!) {
738
+ unshieldedTransactions(address: $address) {
739
+ __typename
740
+ ... on UnshieldedTransaction {
741
+ transaction { id hash }
742
+ createdUtxos { value owner tokenType intentHash outputIndex }
743
+ spentUtxos { value owner tokenType intentHash outputIndex }
744
+ }
745
+ ... on UnshieldedTransactionsProgress {
746
+ highestTransactionId
747
+ }
748
+ }
749
+ }
750
+ `;
751
+ var init_balance_subscription = () => {
752
+ };
753
+
754
+ // src/ui/spinner.ts
755
+ function start(message) {
756
+ if (!isColorEnabled()) {
757
+ process.stderr.write(`⠋ ${message}`);
758
+ return {
759
+ update(msg) {
760
+ process.stderr.write(`\r⠋ ${msg}`);
761
+ },
762
+ stop(finalMessage) {
763
+ const final = finalMessage ?? message;
764
+ process.stderr.write(`\r✓ ${final}
765
+ `);
766
+ }
767
+ };
768
+ }
769
+ let frameIndex = 0;
770
+ let currentMessage = message;
771
+ const render = () => {
772
+ const frame = teal(BRAILLE_FRAMES[frameIndex]);
773
+ process.stderr.write(`\r${frame} ${currentMessage}\x1B[K`);
774
+ frameIndex = (frameIndex + 1) % BRAILLE_FRAMES.length;
775
+ };
776
+ render();
777
+ const timer = setInterval(render, FRAME_INTERVAL_MS);
778
+ return {
779
+ update(msg) {
780
+ currentMessage = msg;
781
+ },
782
+ stop(finalMessage) {
783
+ clearInterval(timer);
784
+ const final = finalMessage ?? currentMessage;
785
+ process.stderr.write(`\r\x1B[32m✓\x1B[0m ${final}\x1B[K
786
+ `);
787
+ }
788
+ };
789
+ }
790
+ var BRAILLE_FRAMES, FRAME_INTERVAL_MS = 80;
791
+ var init_spinner = __esm(() => {
792
+ BRAILLE_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
793
+ });
794
+
795
+ // src/commands/balance.ts
796
+ var exports_balance = {};
797
+ __export(exports_balance, {
798
+ default: () => balanceCommand
799
+ });
800
+ async function balanceCommand(args) {
801
+ let address;
802
+ let walletNetwork;
803
+ if (args.subcommand) {
804
+ address = args.subcommand;
805
+ } else {
806
+ const walletPath = getFlag(args, "wallet");
807
+ const config = loadWalletConfig(walletPath);
808
+ address = config.address;
809
+ walletNetwork = config.network;
810
+ }
811
+ if (!address) {
812
+ throw new Error("No address provided and no wallet file found.");
813
+ }
814
+ const { name: networkName, config: networkConfig } = resolveNetwork({
815
+ args,
816
+ walletNetwork,
817
+ address
818
+ });
819
+ const indexerWsOverride = getFlag(args, "indexer-ws");
820
+ const indexerWS = indexerWsOverride ?? networkConfig.indexerWS;
821
+ const spinner = start(`Checking balance on ${networkName}...`);
822
+ try {
823
+ const result = await checkBalance(address, indexerWS, (current, highest) => {
824
+ if (highest > 0) {
825
+ const pct = Math.round(current / highest * 100);
826
+ spinner.update(`Syncing transactions... ${pct}%`);
827
+ }
828
+ });
829
+ spinner.stop(`Synced ${result.txCount} transactions`);
830
+ if (hasFlag(args, "json")) {
831
+ const balances = {};
832
+ for (const [tokenType, amount] of result.balances) {
833
+ const key = isNativeToken(tokenType) ? "NIGHT" : tokenType;
834
+ balances[key] = isNativeToken(tokenType) ? toNight(amount) : amount.toString();
835
+ }
836
+ writeJsonResult({
837
+ address,
838
+ network: networkName,
839
+ balances,
840
+ utxoCount: result.utxoCount,
841
+ txCount: result.txCount
842
+ });
843
+ return;
844
+ }
845
+ if (result.balances.size === 0) {
846
+ process.stdout.write(`0
847
+ `);
848
+ } else {
849
+ for (const [tokenType, amount] of result.balances) {
850
+ if (isNativeToken(tokenType)) {
851
+ process.stdout.write(`NIGHT=${amount}
852
+ `);
853
+ } else {
854
+ process.stdout.write(`${tokenType}=${amount}
855
+ `);
856
+ }
857
+ }
858
+ }
859
+ process.stderr.write(`
860
+ ` + header("Balance") + `
861
+
862
+ `);
863
+ process.stderr.write(keyValue("Address", formatAddress(address)) + `
864
+ `);
865
+ process.stderr.write(keyValue("Network", networkName) + `
866
+ `);
867
+ process.stderr.write(keyValue("UTXOs", result.utxoCount.toString()) + `
868
+ `);
869
+ process.stderr.write(keyValue("Transactions", result.txCount.toString()) + `
870
+ `);
871
+ process.stderr.write(`
872
+ `);
873
+ if (result.balances.size === 0) {
874
+ process.stderr.write(` ${dim("No balance found")}
875
+ `);
876
+ } else {
877
+ for (const [tokenType, amount] of result.balances) {
878
+ if (isNativeToken(tokenType)) {
879
+ process.stderr.write(keyValue("NIGHT", bold(formatNight(amount))) + `
880
+ `);
881
+ } else {
882
+ const shortType = tokenType.slice(0, 8) + "…" + tokenType.slice(-8);
883
+ process.stderr.write(keyValue(`Token ${shortType}`, bold(amount.toString())) + `
884
+ `);
885
+ }
886
+ }
887
+ }
888
+ process.stderr.write(`
889
+ ` + divider() + `
890
+
891
+ `);
892
+ } catch (err) {
893
+ spinner.stop("Failed");
894
+ throw err;
895
+ }
896
+ }
897
+ var init_balance = __esm(() => {
898
+ init_wallet_config();
899
+ init_resolve_network();
900
+ init_balance_subscription();
901
+ init_format();
902
+ init_spinner();
903
+ });
904
+
905
+ // src/commands/address.ts
906
+ var exports_address = {};
907
+ __export(exports_address, {
908
+ default: () => addressCommand
909
+ });
910
+ async function addressCommand(args) {
911
+ const seedHex = requireFlag(args, "seed", "hex").replace(/^0x/, "");
912
+ if (seedHex.length !== 64 || !/^[0-9a-fA-F]+$/.test(seedHex)) {
913
+ throw new Error("Seed must be a 64-character hex string (32 bytes)");
914
+ }
915
+ const indexStr = getFlag(args, "index");
916
+ const keyIndex = indexStr !== undefined ? parseInt(indexStr, 10) : 0;
917
+ if (isNaN(keyIndex) || keyIndex < 0 || !Number.isInteger(Number(indexStr ?? "0"))) {
918
+ throw new Error("Key index must be a non-negative integer");
919
+ }
920
+ const seedBuffer = Buffer.from(seedHex, "hex");
921
+ const networkName = resolveNetworkName({ args });
922
+ const address = deriveUnshieldedAddress(seedBuffer, networkName, keyIndex);
923
+ const derivationPath = `m/44'/2400'/0'/NightExternal/${keyIndex}`;
924
+ if (hasFlag(args, "json")) {
925
+ writeJsonResult({
926
+ address,
927
+ network: networkName,
928
+ index: keyIndex,
929
+ path: derivationPath
930
+ });
931
+ return;
932
+ }
933
+ process.stdout.write(address + `
934
+ `);
935
+ process.stderr.write(`
936
+ `);
937
+ process.stderr.write(keyValue("Network", networkName) + `
938
+ `);
939
+ process.stderr.write(keyValue("Index", keyIndex.toString()) + `
940
+ `);
941
+ process.stderr.write(keyValue("Address", formatAddress(address)) + `
942
+ `);
943
+ process.stderr.write(keyValue("Path", dim(derivationPath)) + `
944
+ `);
945
+ process.stderr.write(divider() + `
946
+
947
+ `);
948
+ }
949
+ var init_address = __esm(() => {
950
+ init_derive_address();
951
+ init_resolve_network();
952
+ init_format();
953
+ });
954
+
955
+ // src/commands/genesis-address.ts
956
+ var exports_genesis_address = {};
957
+ __export(exports_genesis_address, {
958
+ default: () => genesisAddressCommand
959
+ });
960
+ async function genesisAddressCommand(args) {
961
+ const networkName = resolveNetworkName({ args });
962
+ const seedBuffer = Buffer.from(GENESIS_SEED, "hex");
963
+ const address = deriveUnshieldedAddress(seedBuffer, networkName);
964
+ if (hasFlag(args, "json")) {
965
+ writeJsonResult({ address, network: networkName });
966
+ return;
967
+ }
968
+ process.stdout.write(address + `
969
+ `);
970
+ process.stderr.write(`
971
+ `);
972
+ process.stderr.write(keyValue("Network", networkName) + `
973
+ `);
974
+ process.stderr.write(keyValue("Address", formatAddress(address)) + `
975
+ `);
976
+ process.stderr.write(keyValue("Seed", dim("0x01 (genesis)")) + `
977
+ `);
978
+ process.stderr.write(divider() + `
979
+
980
+ `);
981
+ }
982
+ var init_genesis_address = __esm(() => {
983
+ init_derive_address();
984
+ init_resolve_network();
985
+ init_format();
986
+ });
987
+
988
+ // src/commands/inspect-cost.ts
989
+ var exports_inspect_cost = {};
990
+ __export(exports_inspect_cost, {
991
+ default: () => inspectCostCommand
992
+ });
993
+ import * as ledger from "@midnight-ntwrk/ledger-v7";
994
+ function probeDimension(params, dimension, probeValue) {
995
+ const cost = {
996
+ readTime: 0n,
997
+ computeTime: 0n,
998
+ blockUsage: 0n,
999
+ bytesWritten: 0n,
1000
+ bytesChurned: 0n
1001
+ };
1002
+ cost[dimension] = probeValue;
1003
+ const normalized = params.normalizeFullness(cost);
1004
+ const normalizedValue = normalized[dimension];
1005
+ return Math.round(Number(probeValue) / normalizedValue);
1006
+ }
1007
+ function deriveBlockLimits(params) {
1008
+ return {
1009
+ readTime: probeDimension(params, "readTime", 1000000000n),
1010
+ computeTime: probeDimension(params, "computeTime", 1000000000n),
1011
+ blockUsage: probeDimension(params, "blockUsage", 10000n),
1012
+ bytesWritten: probeDimension(params, "bytesWritten", 10000n),
1013
+ bytesChurned: probeDimension(params, "bytesChurned", 1000000n)
1014
+ };
1015
+ }
1016
+ async function inspectCostCommand(args) {
1017
+ const params = ledger.LedgerParameters.initialParameters();
1018
+ const limits = deriveBlockLimits(params);
1019
+ if (hasFlag(args, "json")) {
1020
+ writeJsonResult(limits);
1021
+ return;
1022
+ }
1023
+ for (const [dimension, value] of Object.entries(limits)) {
1024
+ process.stdout.write(`${dimension}=${value}
1025
+ `);
1026
+ }
1027
+ process.stderr.write(`
1028
+ ` + header("Block Limits") + `
1029
+
1030
+ `);
1031
+ process.stderr.write(dim(" Derived from LedgerParameters.initialParameters()") + `
1032
+
1033
+ `);
1034
+ for (const [dimension, value] of Object.entries(limits)) {
1035
+ const unit = UNITS[dimension] ?? "";
1036
+ process.stderr.write(keyValue(dimension, `${bold(value.toLocaleString())} ${dim(unit)}`) + `
1037
+ `);
1038
+ }
1039
+ process.stderr.write(`
1040
+ ` + divider() + `
1041
+ `);
1042
+ process.stderr.write(dim(" bytesWritten is typically the tightest constraint") + `
1043
+ `);
1044
+ process.stderr.write(dim(" for large contract deployments.") + `
1045
+
1046
+ `);
1047
+ }
1048
+ var UNITS;
1049
+ var init_inspect_cost = __esm(() => {
1050
+ init_format();
1051
+ UNITS = {
1052
+ readTime: "picoseconds",
1053
+ computeTime: "picoseconds",
1054
+ blockUsage: "bytes",
1055
+ bytesWritten: "bytes",
1056
+ bytesChurned: "bytes"
1057
+ };
1058
+ });
1059
+
1060
+ // src/lib/derivation.ts
1061
+ import { HDWallet as HDWallet2, Roles as Roles2 } from "@midnight-ntwrk/wallet-sdk-hd";
1062
+ function deriveKey(seedBuffer, role) {
1063
+ const hdResult = HDWallet2.fromSeed(seedBuffer);
1064
+ if (hdResult.type !== "seedOk") {
1065
+ throw new Error("Invalid seed for HD wallet");
1066
+ }
1067
+ const derivation = hdResult.hdWallet.selectAccount(0).selectRole(role).deriveKeyAt(0);
1068
+ if (derivation.type === "keyOutOfBounds") {
1069
+ throw new Error("Key derivation out of bounds");
1070
+ }
1071
+ return derivation.key;
1072
+ }
1073
+ function deriveShieldedSeed(seedBuffer) {
1074
+ return deriveKey(seedBuffer, Roles2.Zswap);
1075
+ }
1076
+ function deriveUnshieldedSeed(seedBuffer) {
1077
+ return deriveKey(seedBuffer, Roles2.NightExternal);
1078
+ }
1079
+ function deriveDustSeed(seedBuffer) {
1080
+ return deriveKey(seedBuffer, Roles2.Dust);
1081
+ }
1082
+ var init_derivation = () => {
1083
+ };
1084
+
1085
+ // src/lib/facade.ts
1086
+ import { ShieldedWallet } from "@midnight-ntwrk/wallet-sdk-shielded";
1087
+ import {
1088
+ UnshieldedWallet,
1089
+ createKeystore as createKeystore2,
1090
+ PublicKey as PublicKey2,
1091
+ InMemoryTransactionHistoryStorage
1092
+ } from "@midnight-ntwrk/wallet-sdk-unshielded-wallet";
1093
+ import { DustWallet } from "@midnight-ntwrk/wallet-sdk-dust-wallet";
1094
+ import { WalletFacade } from "@midnight-ntwrk/wallet-sdk-facade";
1095
+ import * as ledger2 from "@midnight-ntwrk/ledger-v7";
1096
+ import { NetworkId as NetworkId2 } from "@midnight-ntwrk/wallet-sdk-abstractions";
1097
+ import * as rx from "rxjs";
1098
+ function buildFacade(seedBuffer, networkConfig) {
1099
+ const networkId = NETWORK_ID_MAP2[networkConfig.networkId];
1100
+ if (networkId === undefined) {
1101
+ throw new Error(`Unknown networkId: ${networkConfig.networkId}`);
1102
+ }
1103
+ const shieldedSeed = deriveShieldedSeed(seedBuffer);
1104
+ const unshieldedSeed = deriveUnshieldedSeed(seedBuffer);
1105
+ const dustSeed = deriveDustSeed(seedBuffer);
1106
+ const zswapSecretKeys = ledger2.ZswapSecretKeys.fromSeed(shieldedSeed);
1107
+ const dustSecretKey = ledger2.DustSecretKey.fromSeed(dustSeed);
1108
+ const keystore = createKeystore2(unshieldedSeed, networkId);
1109
+ const shieldedConfig = {
1110
+ networkId,
1111
+ indexerClientConnection: {
1112
+ indexerHttpUrl: networkConfig.indexer,
1113
+ indexerWsUrl: networkConfig.indexerWS
1114
+ },
1115
+ provingServerUrl: new URL(networkConfig.proofServer),
1116
+ relayURL: new URL(networkConfig.node)
1117
+ };
1118
+ const unshieldedConfig = {
1119
+ networkId,
1120
+ indexerClientConnection: {
1121
+ indexerHttpUrl: networkConfig.indexer,
1122
+ indexerWsUrl: networkConfig.indexerWS
1123
+ },
1124
+ txHistoryStorage: new InMemoryTransactionHistoryStorage
1125
+ };
1126
+ const dustConfig = {
1127
+ networkId,
1128
+ costParameters: {
1129
+ additionalFeeOverhead: DUST_COST_OVERHEAD,
1130
+ feeBlocksMargin: DUST_FEE_BLOCKS_MARGIN
1131
+ },
1132
+ indexerClientConnection: {
1133
+ indexerHttpUrl: networkConfig.indexer,
1134
+ indexerWsUrl: networkConfig.indexerWS
1135
+ },
1136
+ provingServerUrl: new URL(networkConfig.proofServer),
1137
+ relayURL: new URL(networkConfig.node)
1138
+ };
1139
+ const shieldedWallet = ShieldedWallet(shieldedConfig).startWithSecretKeys(zswapSecretKeys);
1140
+ const unshieldedWallet = UnshieldedWallet(unshieldedConfig).startWithPublicKey(PublicKey2.fromKeyStore(keystore));
1141
+ const dustWallet = DustWallet(dustConfig).startWithSecretKey(dustSecretKey, ledger2.LedgerParameters.initialParameters().dust);
1142
+ const facade = new WalletFacade(shieldedWallet, unshieldedWallet, dustWallet);
1143
+ return { facade, keystore, zswapSecretKeys, dustSecretKey };
1144
+ }
1145
+ async function startAndSyncFacade(bundle, onProgress) {
1146
+ const { facade, zswapSecretKeys, dustSecretKey } = bundle;
1147
+ await facade.start(zswapSecretKeys, dustSecretKey);
1148
+ return rx.firstValueFrom(facade.state().pipe(rx.tap((state) => {
1149
+ if (onProgress) {
1150
+ const progress = state.unshielded.progress;
1151
+ if (progress) {
1152
+ onProgress(Number(progress.appliedId), Number(progress.highestTransactionId));
1153
+ }
1154
+ }
1155
+ }), rx.filter((state) => state.isSynced), rx.timeout(SYNC_TIMEOUT_MS)));
1156
+ }
1157
+ async function quickSync(bundle) {
1158
+ return rx.firstValueFrom(bundle.facade.state().pipe(rx.filter((state) => state.isSynced), rx.timeout(PRE_SEND_SYNC_TIMEOUT_MS)));
1159
+ }
1160
+ async function stopFacade(bundle) {
1161
+ await bundle.facade.stop();
1162
+ }
1163
+ function suppressSdkTransientErrors(onWarning) {
1164
+ const rejectionHandler = (reason) => {
1165
+ const tag = reason?._tag;
1166
+ if (typeof tag === "string" && tag.startsWith("Wallet.")) {
1167
+ const msg = reason?.message ?? "transient error";
1168
+ onWarning?.(tag, msg);
1169
+ return;
1170
+ }
1171
+ originalConsoleError("Unhandled rejection:", reason);
1172
+ process.exit(1);
1173
+ };
1174
+ const originalConsoleError = console.error;
1175
+ console.error = (...args) => {
1176
+ const firstArg = args[0];
1177
+ if (typeof firstArg === "object" && firstArg?._tag?.startsWith("Wallet.")) {
1178
+ onWarning?.(firstArg._tag, firstArg?.message ?? "transient error");
1179
+ return;
1180
+ }
1181
+ if (typeof firstArg === "string" && firstArg.startsWith("Wallet.")) {
1182
+ onWarning?.("Wallet.Sync", "transient error");
1183
+ return;
1184
+ }
1185
+ originalConsoleError(...args);
1186
+ };
1187
+ process.on("unhandledRejection", rejectionHandler);
1188
+ return () => {
1189
+ process.removeListener("unhandledRejection", rejectionHandler);
1190
+ console.error = originalConsoleError;
1191
+ };
1192
+ }
1193
+ var NETWORK_ID_MAP2;
1194
+ var init_facade = __esm(() => {
1195
+ init_derivation();
1196
+ NETWORK_ID_MAP2 = {
1197
+ PreProd: NetworkId2.NetworkId.PreProd,
1198
+ Preview: NetworkId2.NetworkId.Preview,
1199
+ Undeployed: NetworkId2.NetworkId.Undeployed
1200
+ };
1201
+ });
1202
+
1203
+ // src/lib/transfer.ts
1204
+ import * as ledger3 from "@midnight-ntwrk/ledger-v7";
1205
+ import { MidnightBech32m, UnshieldedAddress } from "@midnight-ntwrk/wallet-sdk-address-format";
1206
+ import { NetworkId as NetworkId3 } from "@midnight-ntwrk/wallet-sdk-abstractions";
1207
+ import * as rx2 from "rxjs";
1208
+ function nightToMicro(amountNight) {
1209
+ if (amountNight <= 0) {
1210
+ throw new Error("Amount must be greater than 0");
1211
+ }
1212
+ if (!Number.isFinite(amountNight)) {
1213
+ throw new Error("Amount must be a finite number");
1214
+ }
1215
+ const str = amountNight.toFixed(6);
1216
+ const [whole, frac] = str.split(".");
1217
+ const microStr = whole + (frac ?? "").padEnd(6, "0");
1218
+ const micro = BigInt(microStr);
1219
+ if (micro <= 0n) {
1220
+ throw new Error("Amount too small — minimum is 0.000001 NIGHT");
1221
+ }
1222
+ return micro;
1223
+ }
1224
+ function parseAmount(amountStr) {
1225
+ const amount = Number(amountStr);
1226
+ if (Number.isNaN(amount) || !Number.isFinite(amount)) {
1227
+ throw new Error(`Invalid amount: "${amountStr}" — must be a positive number`);
1228
+ }
1229
+ if (amount <= 0) {
1230
+ throw new Error(`Invalid amount: "${amountStr}" — must be greater than 0`);
1231
+ }
1232
+ return amount;
1233
+ }
1234
+ function validateRecipientAddress(address, networkConfig) {
1235
+ const networkId = NETWORK_ID_MAP3[networkConfig.networkId];
1236
+ if (networkId === undefined) {
1237
+ throw new Error(`Unknown networkId: ${networkConfig.networkId}`);
1238
+ }
1239
+ try {
1240
+ MidnightBech32m.parse(address).decode(UnshieldedAddress, networkId);
1241
+ } catch (err) {
1242
+ throw new Error(`Invalid recipient address: ${err.message}
1243
+ ` + `Expected a bech32m address for network "${networkConfig.networkId}"`);
1244
+ }
1245
+ }
1246
+ async function ensureDust(bundle, onDust) {
1247
+ const state = await rx2.firstValueFrom(bundle.facade.state().pipe(rx2.filter((s) => s.isSynced)));
1248
+ const nightUtxos = state.unshielded.availableCoins.filter((coin) => coin.meta?.registeredForDustGeneration !== true);
1249
+ if (nightUtxos.length > 0) {
1250
+ onDust?.(`Registering ${nightUtxos.length} UTXO(s) for dust generation...`);
1251
+ const ttl = new Date(Date.now() + TX_TTL_MINUTES * 60 * 1000);
1252
+ const dustReceiverAddress = state.dust.dustAddress;
1253
+ const dustUtxos = nightUtxos.map((coin) => ({
1254
+ ...coin.utxo,
1255
+ ctime: new Date(coin.meta.ctime)
1256
+ }));
1257
+ await bundle.facade.dust.waitForSyncedState();
1258
+ const unprovenTx = await bundle.facade.dust.createDustGenerationTransaction(new Date, ttl, dustUtxos, bundle.keystore.getPublicKey(), dustReceiverAddress);
1259
+ const intent = unprovenTx.intents?.get(1);
1260
+ if (!intent) {
1261
+ throw new Error("Dust generation intent not found on transaction");
1262
+ }
1263
+ const signature = bundle.keystore.signData(intent.signatureData(1));
1264
+ const signedTx = await bundle.facade.dust.addDustGenerationSignature(unprovenTx, signature);
1265
+ const finalized = await bundle.facade.finalizeTransaction(signedTx);
1266
+ await bundle.facade.submitTransaction(finalized);
1267
+ } else if (state.dust.availableCoins.length > 0) {
1268
+ onDust?.("Dust available");
1269
+ return;
1270
+ } else {
1271
+ onDust?.("UTXOs already registered, waiting for dust generation...");
1272
+ }
1273
+ onDust?.("Waiting for dust tokens...");
1274
+ 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)));
1275
+ onDust?.("Dust available");
1276
+ }
1277
+ async function buildAndSubmitTransfer(bundle, recipientAddress, amount, onProving, onSubmitting) {
1278
+ let lastError;
1279
+ for (let attempt = 1;attempt <= MAX_RETRY_ATTEMPTS; attempt++) {
1280
+ try {
1281
+ if (attempt > 1) {
1282
+ await quickSync(bundle);
1283
+ }
1284
+ const ttl = new Date(Date.now() + TX_TTL_MINUTES * 60 * 1000);
1285
+ const unprovenRecipe = await bundle.facade.transferTransaction([
1286
+ {
1287
+ type: "unshielded",
1288
+ outputs: [
1289
+ {
1290
+ amount,
1291
+ receiverAddress: recipientAddress,
1292
+ type: ledger3.unshieldedToken().raw
1293
+ }
1294
+ ]
1295
+ }
1296
+ ], { shieldedSecretKeys: bundle.zswapSecretKeys, dustSecretKey: bundle.dustSecretKey }, { ttl, payFees: true });
1297
+ const signedRecipe = await bundle.facade.signRecipe(unprovenRecipe, (payload) => bundle.keystore.signData(payload));
1298
+ onProving?.();
1299
+ const finalizedTx = await Promise.race([
1300
+ bundle.facade.finalizeRecipe(signedRecipe),
1301
+ new Promise((_, reject) => {
1302
+ setTimeout(() => reject(new Error("ZK proof generation timed out")), PROOF_TIMEOUT_MS);
1303
+ })
1304
+ ]);
1305
+ onSubmitting?.();
1306
+ const txHash = await bundle.facade.submitTransaction(finalizedTx);
1307
+ return txHash;
1308
+ } catch (err) {
1309
+ lastError = err;
1310
+ const isStaleUtxo = err?.code === STALE_UTXO_ERROR_CODE || err?.message?.includes("115") || err?.message?.toLowerCase().includes("stale");
1311
+ if (isStaleUtxo && attempt < MAX_RETRY_ATTEMPTS) {
1312
+ continue;
1313
+ }
1314
+ throw err;
1315
+ }
1316
+ }
1317
+ throw lastError ?? new Error("Transfer failed after retries");
1318
+ }
1319
+ async function executeTransfer(params) {
1320
+ const {
1321
+ seedBuffer,
1322
+ networkConfig,
1323
+ recipientAddress,
1324
+ amountNight,
1325
+ signal,
1326
+ onSync,
1327
+ onDust,
1328
+ onProving,
1329
+ onSubmitting,
1330
+ onSyncWarning
1331
+ } = params;
1332
+ const amount = nightToMicro(amountNight);
1333
+ validateRecipientAddress(recipientAddress, networkConfig);
1334
+ const unsuppress = suppressSdkTransientErrors(onSyncWarning);
1335
+ const bundle = buildFacade(seedBuffer, networkConfig);
1336
+ let shutdownComplete = false;
1337
+ const cleanup = async () => {
1338
+ if (!shutdownComplete) {
1339
+ shutdownComplete = true;
1340
+ try {
1341
+ await stopFacade(bundle);
1342
+ } catch {
1343
+ }
1344
+ }
1345
+ };
1346
+ const onAbort = () => {
1347
+ cleanup();
1348
+ };
1349
+ signal?.addEventListener("abort", onAbort, { once: true });
1350
+ try {
1351
+ const syncedState = await startAndSyncFacade(bundle, onSync);
1352
+ if (signal?.aborted)
1353
+ throw new Error("Operation cancelled");
1354
+ const unshieldedBalance = syncedState.unshielded.balances[ledger3.unshieldedToken().raw] ?? 0n;
1355
+ if (unshieldedBalance < amount) {
1356
+ const haveNight = Number(unshieldedBalance) / TOKEN_MULTIPLIER;
1357
+ throw new Error(`Insufficient balance: ${haveNight.toFixed(6)} NIGHT available, ` + `${amountNight} NIGHT requested`);
1358
+ }
1359
+ if (signal?.aborted)
1360
+ throw new Error("Operation cancelled");
1361
+ await ensureDust(bundle, onDust);
1362
+ if (signal?.aborted)
1363
+ throw new Error("Operation cancelled");
1364
+ const txHash = await buildAndSubmitTransfer(bundle, recipientAddress, amount, onProving, onSubmitting);
1365
+ return { txHash, amountMicroNight: amount };
1366
+ } finally {
1367
+ signal?.removeEventListener("abort", onAbort);
1368
+ unsuppress();
1369
+ await cleanup();
1370
+ }
1371
+ }
1372
+ var NETWORK_ID_MAP3;
1373
+ var init_transfer = __esm(() => {
1374
+ init_facade();
1375
+ NETWORK_ID_MAP3 = {
1376
+ PreProd: NetworkId3.NetworkId.PreProd,
1377
+ Preview: NetworkId3.NetworkId.Preview,
1378
+ Undeployed: NetworkId3.NetworkId.Undeployed
1379
+ };
1380
+ });
1381
+
1382
+ // src/commands/airdrop.ts
1383
+ var exports_airdrop = {};
1384
+ __export(exports_airdrop, {
1385
+ default: () => airdropCommand
1386
+ });
1387
+ async function airdropCommand(args, signal) {
1388
+ const amountStr = args.subcommand;
1389
+ if (!amountStr) {
1390
+ throw new Error(`Missing amount.
1391
+ ` + `Usage: midnight airdrop <amount>
1392
+ ` + "Example: midnight airdrop 1000");
1393
+ }
1394
+ const amountNight = parseAmount(amountStr);
1395
+ const walletPath = getFlag(args, "wallet");
1396
+ const config = loadWalletConfig(walletPath);
1397
+ const { name: networkName, config: networkConfig } = resolveNetwork({
1398
+ args,
1399
+ walletNetwork: config.network,
1400
+ address: config.address
1401
+ });
1402
+ if (networkName !== "undeployed") {
1403
+ throw new Error(`Airdrop is only available on the "undeployed" network (local devnet).
1404
+ ` + `Current network: "${networkName}"
1405
+ ` + `On preprod/preview, use a faucet or transfer from another wallet.`);
1406
+ }
1407
+ const recipientAddress = config.address;
1408
+ const genesisSeedBuffer = Buffer.from(GENESIS_SEED, "hex");
1409
+ process.stderr.write(`
1410
+ ` + header("Airdrop") + `
1411
+
1412
+ `);
1413
+ process.stderr.write(keyValue("Network", networkName) + `
1414
+ `);
1415
+ process.stderr.write(keyValue("From", dim("genesis (seed 0x01)")) + `
1416
+ `);
1417
+ process.stderr.write(keyValue("To", formatAddress(recipientAddress, true)) + `
1418
+ `);
1419
+ process.stderr.write(keyValue("Amount", bold(amountNight + " NIGHT")) + `
1420
+ `);
1421
+ process.stderr.write(`
1422
+ `);
1423
+ const spinner = start("Starting genesis wallet...");
1424
+ try {
1425
+ const result = await executeTransfer({
1426
+ seedBuffer: genesisSeedBuffer,
1427
+ networkConfig,
1428
+ recipientAddress,
1429
+ amountNight,
1430
+ signal,
1431
+ onSync(applied, highest) {
1432
+ if (highest > 0) {
1433
+ const pct = Math.round(applied / highest * 100);
1434
+ spinner.update(`Syncing genesis wallet... ${pct}%`);
1435
+ }
1436
+ },
1437
+ onDust(status) {
1438
+ spinner.update(`Dust: ${status}`);
1439
+ },
1440
+ onProving() {
1441
+ spinner.update("Generating ZK proof (this may take a few minutes)...");
1442
+ },
1443
+ onSubmitting() {
1444
+ spinner.update("Submitting transaction...");
1445
+ },
1446
+ onSyncWarning(_tag, msg) {
1447
+ spinner.update(`Syncing genesis wallet... (${msg}, retrying)`);
1448
+ }
1449
+ });
1450
+ spinner.stop("Transaction submitted");
1451
+ if (hasFlag(args, "json")) {
1452
+ writeJsonResult({
1453
+ txHash: result.txHash,
1454
+ amount: amountNight,
1455
+ recipient: recipientAddress,
1456
+ network: networkName
1457
+ });
1458
+ return;
1459
+ }
1460
+ process.stdout.write(result.txHash + `
1461
+ `);
1462
+ process.stderr.write(`
1463
+ ` + successMessage(`Airdropped ${amountNight} NIGHT to your wallet`, result.txHash) + `
1464
+ `);
1465
+ process.stderr.write(`
1466
+ ` + divider() + `
1467
+ `);
1468
+ process.stderr.write(dim(" Verify: midnight balance") + `
1469
+
1470
+ `);
1471
+ } catch (err) {
1472
+ spinner.stop("Failed");
1473
+ if (err instanceof Error && err.message.toLowerCase().includes("dust")) {
1474
+ throw new Error(`${err.message}
1475
+
1476
+ ` + `On a fresh localnet, the minimum airdrop is ~1 NIGHT.
1477
+ ` + `Try: midnight airdrop 1`);
1478
+ }
1479
+ throw err;
1480
+ }
1481
+ }
1482
+ var init_airdrop = __esm(() => {
1483
+ init_wallet_config();
1484
+ init_resolve_network();
1485
+ init_transfer();
1486
+ init_format();
1487
+ init_spinner();
1488
+ });
1489
+
1490
+ // src/commands/transfer.ts
1491
+ var exports_transfer = {};
1492
+ __export(exports_transfer, {
1493
+ default: () => transferCommand
1494
+ });
1495
+ async function transferCommand(args, signal) {
1496
+ const recipientAddress = args.subcommand;
1497
+ const amountStr = args.positionals[0];
1498
+ if (!recipientAddress) {
1499
+ throw new Error(`Missing recipient address.
1500
+ ` + `Usage: midnight transfer <to> <amount>
1501
+ ` + "Example: midnight transfer mn_addr_undeployed1... 100");
1502
+ }
1503
+ if (!amountStr) {
1504
+ throw new Error(`Missing amount.
1505
+ ` + `Usage: midnight transfer <to> <amount>
1506
+ ` + "Example: midnight transfer mn_addr_undeployed1... 100");
1507
+ }
1508
+ const amountNight = parseAmount(amountStr);
1509
+ const walletPath = getFlag(args, "wallet");
1510
+ const config = loadWalletConfig(walletPath);
1511
+ const seedBuffer = Buffer.from(config.seed, "hex");
1512
+ const { name: networkName, config: networkConfig } = resolveNetwork({
1513
+ args,
1514
+ walletNetwork: config.network,
1515
+ address: config.address
1516
+ });
1517
+ process.stderr.write(`
1518
+ ` + header("Transfer") + `
1519
+
1520
+ `);
1521
+ process.stderr.write(keyValue("Network", networkName) + `
1522
+ `);
1523
+ process.stderr.write(keyValue("From", formatAddress(config.address, true)) + `
1524
+ `);
1525
+ process.stderr.write(keyValue("To", formatAddress(recipientAddress, true)) + `
1526
+ `);
1527
+ process.stderr.write(keyValue("Amount", bold(amountNight + " NIGHT")) + `
1528
+ `);
1529
+ process.stderr.write(`
1530
+ `);
1531
+ const spinner = start("Starting wallet...");
1532
+ try {
1533
+ const result = await executeTransfer({
1534
+ seedBuffer,
1535
+ networkConfig,
1536
+ recipientAddress,
1537
+ amountNight,
1538
+ signal,
1539
+ onSync(applied, highest) {
1540
+ if (highest > 0) {
1541
+ const pct = Math.round(applied / highest * 100);
1542
+ spinner.update(`Syncing wallet... ${pct}%`);
1543
+ }
1544
+ },
1545
+ onDust(status) {
1546
+ spinner.update(`Dust: ${status}`);
1547
+ },
1548
+ onProving() {
1549
+ spinner.update("Generating ZK proof (this may take a few minutes)...");
1550
+ },
1551
+ onSubmitting() {
1552
+ spinner.update("Submitting transaction...");
1553
+ },
1554
+ onSyncWarning(_tag, msg) {
1555
+ spinner.update(`Syncing wallet... (${msg}, retrying)`);
1556
+ }
1557
+ });
1558
+ spinner.stop("Transaction submitted");
1559
+ if (hasFlag(args, "json")) {
1560
+ writeJsonResult({
1561
+ txHash: result.txHash,
1562
+ amount: amountNight,
1563
+ recipient: recipientAddress,
1564
+ network: networkName
1565
+ });
1566
+ return;
1567
+ }
1568
+ process.stdout.write(result.txHash + `
1569
+ `);
1570
+ process.stderr.write(`
1571
+ ` + successMessage(`Transferred ${amountNight} NIGHT`, result.txHash) + `
1572
+ `);
1573
+ process.stderr.write(`
1574
+ ` + divider() + `
1575
+ `);
1576
+ process.stderr.write(dim(" Verify: midnight balance") + `
1577
+
1578
+ `);
1579
+ } catch (err) {
1580
+ spinner.stop("Failed");
1581
+ throw err;
1582
+ }
1583
+ }
1584
+ var init_transfer2 = __esm(() => {
1585
+ init_wallet_config();
1586
+ init_resolve_network();
1587
+ init_transfer();
1588
+ init_format();
1589
+ init_spinner();
1590
+ });
1591
+
1592
+ // src/commands/dust.ts
1593
+ var exports_dust = {};
1594
+ __export(exports_dust, {
1595
+ default: () => dustCommand
1596
+ });
1597
+ import * as ledger4 from "@midnight-ntwrk/ledger-v7";
1598
+ import * as rx3 from "rxjs";
1599
+ async function dustCommand(args, signal) {
1600
+ const subcommand = args.subcommand;
1601
+ if (!subcommand || subcommand !== "register" && subcommand !== "status") {
1602
+ throw new Error(`Missing or invalid subcommand.
1603
+ ` + `Usage:
1604
+ ` + ` midnight dust register Register NIGHT UTXOs for dust generation
1605
+ ` + " midnight dust status Check dust registration status");
1606
+ }
1607
+ const walletPath = getFlag(args, "wallet");
1608
+ const config = loadWalletConfig(walletPath);
1609
+ const seedBuffer = Buffer.from(config.seed, "hex");
1610
+ const { name: networkName, config: networkConfig } = resolveNetwork({
1611
+ args,
1612
+ walletNetwork: config.network,
1613
+ address: config.address
1614
+ });
1615
+ const bundle = buildFacade(seedBuffer, networkConfig);
1616
+ const cleanup = async () => {
1617
+ try {
1618
+ await stopFacade(bundle);
1619
+ } catch {
1620
+ }
1621
+ };
1622
+ const onAbort = () => {
1623
+ cleanup();
1624
+ };
1625
+ signal?.addEventListener("abort", onAbort, { once: true });
1626
+ const warningRef = {};
1627
+ const unsuppress = suppressSdkTransientErrors((tag, msg) => {
1628
+ warningRef.current?.(tag, msg);
1629
+ });
1630
+ const isJson = hasFlag(args, "json");
1631
+ try {
1632
+ if (subcommand === "register") {
1633
+ await dustRegister(bundle, networkName, isJson, signal, warningRef);
1634
+ } else {
1635
+ await dustStatus(bundle, networkName, isJson, signal, warningRef);
1636
+ }
1637
+ } finally {
1638
+ signal?.removeEventListener("abort", onAbort);
1639
+ unsuppress();
1640
+ await cleanup();
1641
+ }
1642
+ }
1643
+ async function dustRegister(bundle, networkName, jsonMode, signal, warningRef) {
1644
+ process.stderr.write(`
1645
+ ` + header("Dust Register") + `
1646
+
1647
+ `);
1648
+ process.stderr.write(keyValue("Network", networkName) + `
1649
+
1650
+ `);
1651
+ const spinner = start("Syncing wallet...");
1652
+ if (warningRef) {
1653
+ warningRef.current = (_tag, msg) => spinner.update(`Syncing wallet... (${msg}, retrying)`);
1654
+ }
1655
+ try {
1656
+ await startAndSyncFacade(bundle, (applied, highest) => {
1657
+ if (highest > 0) {
1658
+ const pct = Math.round(applied / highest * 100);
1659
+ spinner.update(`Syncing wallet... ${pct}%`);
1660
+ }
1661
+ });
1662
+ if (signal?.aborted)
1663
+ throw new Error("Operation cancelled");
1664
+ spinner.update("Checking dust status...");
1665
+ const state = await rx3.firstValueFrom(bundle.facade.state().pipe(rx3.filter((s) => s.isSynced)));
1666
+ if (state.dust.availableCoins.length > 0) {
1667
+ const dustBal2 = state.dust.walletBalance(new Date);
1668
+ spinner.stop("Dust already available");
1669
+ if (jsonMode) {
1670
+ writeJsonResult({ subcommand: "register", dustBalance: toDust(dustBal2) });
1671
+ return;
1672
+ }
1673
+ process.stdout.write(dustBal2.toString() + `
1674
+ `);
1675
+ process.stderr.write(`
1676
+ ` + successMessage(`Dust tokens already available: ${formatDust(dustBal2)}`) + `
1677
+
1678
+ `);
1679
+ return;
1680
+ }
1681
+ const nightUtxos = state.unshielded.availableCoins.filter((coin) => coin.meta?.registeredForDustGeneration !== true);
1682
+ let txHash;
1683
+ if (nightUtxos.length === 0) {
1684
+ spinner.update("All UTXOs already registered, waiting for dust generation...");
1685
+ } else {
1686
+ spinner.update(`Registering ${nightUtxos.length} UTXO(s) for dust generation...`);
1687
+ const ttl = new Date(Date.now() + TX_TTL_MINUTES * 60 * 1000);
1688
+ const dustReceiverAddress = state.dust.dustAddress;
1689
+ const dustUtxos = nightUtxos.map((coin) => ({
1690
+ ...coin.utxo,
1691
+ ctime: new Date(coin.meta.ctime)
1692
+ }));
1693
+ await bundle.facade.dust.waitForSyncedState();
1694
+ const unprovenTx = await bundle.facade.dust.createDustGenerationTransaction(new Date, ttl, dustUtxos, bundle.keystore.getPublicKey(), dustReceiverAddress);
1695
+ const intent = unprovenTx.intents?.get(1);
1696
+ if (!intent) {
1697
+ throw new Error("Dust generation intent not found on transaction");
1698
+ }
1699
+ const signature = bundle.keystore.signData(intent.signatureData(1));
1700
+ const signedTx = await bundle.facade.dust.addDustGenerationSignature(unprovenTx, signature);
1701
+ const finalized = await bundle.facade.finalizeTransaction(signedTx);
1702
+ txHash = await bundle.facade.submitTransaction(finalized);
1703
+ spinner.update(`Registration submitted (${txHash.slice(0, 12)}...), waiting for dust...`);
1704
+ }
1705
+ if (signal?.aborted)
1706
+ throw new Error("Operation cancelled");
1707
+ 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)));
1708
+ const dustBal = dustState.dust.walletBalance(new Date);
1709
+ spinner.stop("Dust registration complete");
1710
+ if (jsonMode) {
1711
+ const result = { subcommand: "register", dustBalance: toDust(dustBal) };
1712
+ if (txHash)
1713
+ result.txHash = txHash;
1714
+ writeJsonResult(result);
1715
+ return;
1716
+ }
1717
+ process.stdout.write(dustBal.toString() + `
1718
+ `);
1719
+ process.stderr.write(`
1720
+ ` + successMessage(`Dust tokens available: ${formatDust(dustBal)}`) + `
1721
+
1722
+ `);
1723
+ } catch (err) {
1724
+ spinner.stop("Failed");
1725
+ throw err;
1726
+ }
1727
+ }
1728
+ async function dustStatus(bundle, networkName, jsonMode, signal, warningRef) {
1729
+ process.stderr.write(`
1730
+ ` + header("Dust Status") + `
1731
+
1732
+ `);
1733
+ process.stderr.write(keyValue("Network", networkName) + `
1734
+
1735
+ `);
1736
+ const spinner = start("Syncing wallet...");
1737
+ if (warningRef) {
1738
+ warningRef.current = (_tag, msg) => spinner.update(`Syncing wallet... (${msg}, retrying)`);
1739
+ }
1740
+ try {
1741
+ await startAndSyncFacade(bundle, (applied, highest) => {
1742
+ if (highest > 0) {
1743
+ const pct = Math.round(applied / highest * 100);
1744
+ spinner.update(`Syncing wallet... ${pct}%`);
1745
+ }
1746
+ });
1747
+ if (signal?.aborted)
1748
+ throw new Error("Operation cancelled");
1749
+ spinner.update("Checking dust status...");
1750
+ const state = await rx3.firstValueFrom(bundle.facade.state().pipe(rx3.filter((s) => s.isSynced)));
1751
+ const dustBalance = state.dust.walletBalance(new Date);
1752
+ const hasAvailableDust = state.dust.availableCoins.length > 0;
1753
+ const allUtxos = state.unshielded.availableCoins;
1754
+ const unregisteredUtxos = allUtxos.filter((coin) => coin.meta?.registeredForDustGeneration !== true);
1755
+ const registeredCount = allUtxos.length - unregisteredUtxos.length;
1756
+ const unshieldedBalance = state.unshielded.balances[ledger4.unshieldedToken().raw] ?? 0n;
1757
+ spinner.stop("Done");
1758
+ if (jsonMode) {
1759
+ writeJsonResult({
1760
+ subcommand: "status",
1761
+ dustBalance: toDust(dustBalance),
1762
+ registered: registeredCount,
1763
+ unregistered: unregisteredUtxos.length,
1764
+ nightBalance: toNight(unshieldedBalance),
1765
+ dustAvailable: hasAvailableDust
1766
+ });
1767
+ return;
1768
+ }
1769
+ process.stdout.write(`dust=${dustBalance}
1770
+ `);
1771
+ process.stdout.write(`registered=${registeredCount}
1772
+ `);
1773
+ process.stdout.write(`unregistered=${unregisteredUtxos.length}
1774
+ `);
1775
+ process.stderr.write(keyValue("NIGHT Balance", bold(formatNight(unshieldedBalance))) + `
1776
+ `);
1777
+ process.stderr.write(keyValue("Dust Balance", bold(formatDust(dustBalance))) + `
1778
+ `);
1779
+ process.stderr.write(keyValue("Dust Available", hasAvailableDust ? "yes" : "no") + `
1780
+ `);
1781
+ process.stderr.write(keyValue("Registered", registeredCount.toString() + " UTXO(s)") + `
1782
+ `);
1783
+ process.stderr.write(keyValue("Unregistered", unregisteredUtxos.length.toString() + " UTXO(s)") + `
1784
+ `);
1785
+ process.stderr.write(`
1786
+ ` + divider() + `
1787
+
1788
+ `);
1789
+ } catch (err) {
1790
+ spinner.stop("Failed");
1791
+ throw err;
1792
+ }
1793
+ }
1794
+ var init_dust = __esm(() => {
1795
+ init_wallet_config();
1796
+ init_resolve_network();
1797
+ init_facade();
1798
+ init_format();
1799
+ init_spinner();
1800
+ });
1801
+
1802
+ // src/commands/config.ts
1803
+ var exports_config = {};
1804
+ __export(exports_config, {
1805
+ default: () => configCommand
1806
+ });
1807
+ async function configCommand(args) {
1808
+ const action = args.subcommand;
1809
+ if (!action || action !== "get" && action !== "set") {
1810
+ throw new Error(`Usage: midnight config <get|set> <key> [value]
1811
+ ` + `Valid keys: ${getValidConfigKeys().join(", ")}`);
1812
+ }
1813
+ const key = args.positionals[0];
1814
+ if (!key) {
1815
+ throw new Error(`Missing config key.
1816
+ ` + `Valid keys: ${getValidConfigKeys().join(", ")}`);
1817
+ }
1818
+ if (action === "get") {
1819
+ const value = getConfigValue(key);
1820
+ if (hasFlag(args, "json")) {
1821
+ writeJsonResult({ action: "get", key, value });
1822
+ return;
1823
+ }
1824
+ process.stdout.write(value + `
1825
+ `);
1826
+ } else {
1827
+ const value = args.positionals[1];
1828
+ if (value === undefined) {
1829
+ throw new Error(`Missing value for config set.
1830
+ Usage: midnight config set ${key} <value>`);
1831
+ }
1832
+ setConfigValue(key, value);
1833
+ if (hasFlag(args, "json")) {
1834
+ writeJsonResult({ action: "set", key, value });
1835
+ return;
1836
+ }
1837
+ process.stderr.write(green("✓") + ` ${key} = ${value}
1838
+ `);
1839
+ }
1840
+ }
1841
+ var init_config = __esm(() => {
1842
+ init_cli_config();
1843
+ });
1844
+
1845
+ // src/lib/localnet.ts
1846
+ import { execSync as execSync2 } from "child_process";
1847
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
1848
+ import { homedir as homedir5 } from "os";
1849
+ import { join as join5 } from "path";
1850
+ function checkDockerAvailable() {
1851
+ try {
1852
+ const output = execSync2("docker compose version", { ...EXEC_OPTIONS, timeout: 1e4 });
1853
+ return output.trim();
1854
+ } catch {
1855
+ try {
1856
+ execSync2("docker --version", { ...EXEC_OPTIONS, timeout: 5000 });
1857
+ throw new Error(`Docker Compose v2 is required.
1858
+ ` + "Install it from https://docs.docker.com/compose/install/");
1859
+ } catch (innerErr) {
1860
+ if (innerErr instanceof Error && innerErr.message.includes("Docker Compose v2")) {
1861
+ throw innerErr;
1862
+ }
1863
+ throw new Error(`Docker is required but was not found.
1864
+ ` + "Install Docker from https://docs.docker.com/get-docker/");
1865
+ }
1866
+ }
1867
+ }
1868
+ function ensureComposeFile() {
1869
+ const versionMatches = existsSync4(VERSION_PATH) && existsSync4(COMPOSE_PATH) && readFileSync3(VERSION_PATH, "utf-8").trim() === COMPOSE_VERSION;
1870
+ if (versionMatches)
1871
+ return false;
1872
+ mkdirSync3(LOCALNET_DIR, { recursive: true, mode: DIR_MODE });
1873
+ writeFileSync3(COMPOSE_PATH, COMPOSE_YAML, "utf-8");
1874
+ writeFileSync3(VERSION_PATH, COMPOSE_VERSION, "utf-8");
1875
+ return true;
1876
+ }
1877
+ function dockerCompose(args) {
1878
+ return execSync2(`docker compose -f "${COMPOSE_PATH}" ${args}`, EXEC_OPTIONS);
1879
+ }
1880
+ function getServiceStatus() {
1881
+ try {
1882
+ const output = dockerCompose("ps --format json");
1883
+ if (!output.trim())
1884
+ return [];
1885
+ const lines = output.trim().split(`
1886
+ `);
1887
+ const services = [];
1888
+ for (const line of lines) {
1889
+ if (!line.trim())
1890
+ continue;
1891
+ try {
1892
+ const obj = JSON.parse(line);
1893
+ const name = obj.Service ?? "unknown";
1894
+ services.push({
1895
+ name,
1896
+ state: obj.State ?? "unknown",
1897
+ health: obj.Health ?? "",
1898
+ port: PORT_MAP[name] ?? ""
1899
+ });
1900
+ } catch {
1901
+ }
1902
+ }
1903
+ return services;
1904
+ } catch {
1905
+ return [];
1906
+ }
1907
+ }
1908
+ function waitForHealthy(timeoutMs = 120000, intervalMs = 3000) {
1909
+ const deadline = Date.now() + timeoutMs;
1910
+ while (Date.now() < deadline) {
1911
+ const services = getServiceStatus();
1912
+ const allRunning = services.length === 3 && services.every((s) => s.state === "running");
1913
+ if (allRunning) {
1914
+ const healthyOrNoCheck = services.every((s) => s.health === "healthy" || s.health === "");
1915
+ if (healthyOrNoCheck)
1916
+ return true;
1917
+ }
1918
+ execSync2(`sleep ${intervalMs / 1000}`, { timeout: intervalMs + 1000 });
1919
+ }
1920
+ return false;
1921
+ }
1922
+ function getComposePath() {
1923
+ return COMPOSE_PATH;
1924
+ }
1925
+ function removeConflictingContainers() {
1926
+ const removed = [];
1927
+ for (const name of CONTAINER_NAMES) {
1928
+ try {
1929
+ execSync2(`docker rm -f "${name}"`, { ...EXEC_OPTIONS, timeout: 1e4 });
1930
+ removed.push(name);
1931
+ } catch {
1932
+ }
1933
+ }
1934
+ return removed;
1935
+ }
1936
+ var COMPOSE_VERSION = "1.4.0", LOCALNET_DIR, COMPOSE_PATH, VERSION_PATH, COMPOSE_YAML = `services:
1937
+ proof-server:
1938
+ image: 'nel349/proof-server:7.0.0'
1939
+ container_name: "proof-server"
1940
+ ports:
1941
+ - "6300:6300"
1942
+
1943
+ indexer:
1944
+ image: 'midnightntwrk/indexer-standalone:3.0.0'
1945
+ container_name: "indexer"
1946
+ ports:
1947
+ - '8088:8088'
1948
+ environment:
1949
+ RUST_LOG: "indexer=info,chain_indexer=info,indexer_api=info,wallet_indexer=info,indexer_common=info,fastrace_opentelemetry=info,info"
1950
+ # Random 32-byte hex-encoded secret used to make the standalone indexer run.
1951
+ # Only needed to satisfy the config schema – not meant for secure use.
1952
+ APP__INFRA__SECRET: "303132333435363738393031323334353637383930313233343536373839303132"
1953
+ APP__INFRA__NODE__URL: "ws://node:9944"
1954
+ healthcheck:
1955
+ test: ["CMD-SHELL", "cat /var/run/indexer-standalone/running"]
1956
+ start_interval: "5s"
1957
+ interval: "5s"
1958
+ timeout: "2s"
1959
+ retries: 2
1960
+ start_period: 5s
1961
+ depends_on:
1962
+ node:
1963
+ condition: service_started
1964
+
1965
+ node:
1966
+ image: 'midnightntwrk/midnight-node:0.20.1'
1967
+ container_name: "node"
1968
+ ports:
1969
+ - "9944:9944"
1970
+ healthcheck:
1971
+ test: ["CMD", "curl", "-f", "http://localhost:9944/health"]
1972
+ interval: 2s
1973
+ timeout: 5s
1974
+ retries: 5
1975
+ start_period: 5s
1976
+ environment:
1977
+ CFG_PRESET: "dev"
1978
+ `, EXEC_OPTIONS, PORT_MAP, CONTAINER_NAMES;
1979
+ var init_localnet = __esm(() => {
1980
+ LOCALNET_DIR = join5(homedir5(), MIDNIGHT_DIR, LOCALNET_DIR_NAME);
1981
+ COMPOSE_PATH = join5(LOCALNET_DIR, "compose.yml");
1982
+ VERSION_PATH = join5(LOCALNET_DIR, ".version");
1983
+ EXEC_OPTIONS = {
1984
+ encoding: "utf-8",
1985
+ timeout: 30000
1986
+ };
1987
+ PORT_MAP = {
1988
+ node: "9944",
1989
+ indexer: "8088",
1990
+ "proof-server": "6300"
1991
+ };
1992
+ CONTAINER_NAMES = ["node", "indexer", "proof-server"];
1993
+ });
1994
+
1995
+ // src/commands/localnet.ts
1996
+ var exports_localnet = {};
1997
+ __export(exports_localnet, {
1998
+ default: () => localnetCommand
1999
+ });
2000
+ import { spawn } from "child_process";
2001
+ function isValidSubcommand(s) {
2002
+ return VALID_SUBCOMMANDS.includes(s);
2003
+ }
2004
+ function formatServiceTable(services) {
2005
+ const lines = [];
2006
+ for (const svc of services) {
2007
+ const stateColor = svc.state === "running" ? green : red;
2008
+ const healthStr = svc.health ? ` (${svc.health})` : "";
2009
+ const portStr = svc.port ? `:${svc.port}` : "";
2010
+ lines.push(` ${svc.name.padEnd(16)}${stateColor(svc.state)}${dim(healthStr)}${dim(portStr)}`);
2011
+ }
2012
+ return lines.join(`
2013
+ `);
2014
+ }
2015
+ async function handleUp(jsonMode) {
2016
+ const wrote = ensureComposeFile();
2017
+ if (wrote) {
2018
+ process.stderr.write(dim(` Wrote compose.yml to ${getComposePath()}`) + `
2019
+ `);
2020
+ }
2021
+ const spinner = start("Starting local network...");
2022
+ try {
2023
+ dockerCompose("up -d");
2024
+ spinner.update("Waiting for services to be healthy...");
2025
+ const healthy = waitForHealthy(120000);
2026
+ if (!healthy) {
2027
+ spinner.stop(yellow("Services started but not all healthy yet"));
2028
+ process.stderr.write(`
2029
+ ` + dim(" Tip: run ") + bold("midnight localnet logs") + dim(" to check for errors") + `
2030
+ `);
2031
+ } else {
2032
+ spinner.stop("Local network is running");
2033
+ }
2034
+ } catch (err) {
2035
+ spinner.stop(red("Failed to start local network"));
2036
+ if (err instanceof Error) {
2037
+ if (err.message.includes("is already in use by container")) {
2038
+ throw new Error(`Container name conflict — containers with the same names already exist
2039
+ ` + `(likely from a previous midnight-local-network setup).
2040
+
2041
+ ` + 'Run "midnight localnet clean" to remove them, then try again.');
2042
+ }
2043
+ if (err.message.includes("address already in use")) {
2044
+ throw new Error(`Port conflict detected — another process is using a required port.
2045
+ ` + "Check ports 9944, 8088, and 6300, then try again.");
2046
+ }
2047
+ }
2048
+ throw err;
2049
+ }
2050
+ const services = getServiceStatus();
2051
+ if (jsonMode) {
2052
+ writeJsonResult({
2053
+ subcommand: "up",
2054
+ services: services.map((s) => ({ name: s.name, state: s.state, port: s.port, health: s.health }))
2055
+ });
2056
+ return;
2057
+ }
2058
+ if (services.length > 0) {
2059
+ process.stderr.write(`
2060
+ ` + formatServiceTable(services) + `
2061
+ `);
2062
+ }
2063
+ for (const svc of services) {
2064
+ process.stdout.write(`${svc.name}=${svc.state}:${svc.port}
2065
+ `);
2066
+ }
2067
+ process.stderr.write(`
2068
+ ` + dim(" Next: ") + bold("midnight generate --network undeployed") + `
2069
+ `);
2070
+ }
2071
+ async function handleStop(jsonMode) {
2072
+ const spinner = start("Stopping local network...");
2073
+ try {
2074
+ dockerCompose("stop");
2075
+ spinner.stop("Local network stopped (containers preserved)");
2076
+ if (jsonMode) {
2077
+ writeJsonResult({ subcommand: "stop", status: "stopped" });
2078
+ return;
2079
+ }
2080
+ } catch (err) {
2081
+ spinner.stop(red("Failed to stop local network"));
2082
+ throw err;
2083
+ }
2084
+ }
2085
+ async function handleDown(jsonMode) {
2086
+ const spinner = start("Tearing down local network...");
2087
+ try {
2088
+ dockerCompose("down --volumes");
2089
+ spinner.stop("Local network removed (containers, networks, volumes)");
2090
+ if (jsonMode) {
2091
+ writeJsonResult({ subcommand: "down", status: "removed" });
2092
+ return;
2093
+ }
2094
+ } catch (err) {
2095
+ spinner.stop(red("Failed to tear down local network"));
2096
+ throw err;
2097
+ }
2098
+ }
2099
+ async function handleStatus(jsonMode) {
2100
+ const services = getServiceStatus();
2101
+ if (jsonMode) {
2102
+ writeJsonResult({
2103
+ subcommand: "status",
2104
+ services: services.map((s) => ({ name: s.name, state: s.state, port: s.port, health: s.health }))
2105
+ });
2106
+ return;
2107
+ }
2108
+ if (services.length === 0) {
2109
+ process.stderr.write(`
2110
+ ` + header("Localnet Status") + `
2111
+
2112
+ `);
2113
+ process.stderr.write(dim(" No services running.") + `
2114
+ `);
2115
+ process.stderr.write(dim(" Run ") + bold("midnight localnet up") + dim(" to start.") + `
2116
+
2117
+ `);
2118
+ return;
2119
+ }
2120
+ process.stderr.write(`
2121
+ ` + header("Localnet Status") + `
2122
+
2123
+ `);
2124
+ process.stderr.write(formatServiceTable(services) + `
2125
+ `);
2126
+ process.stderr.write(`
2127
+ ` + divider() + `
2128
+
2129
+ `);
2130
+ for (const svc of services) {
2131
+ process.stdout.write(`${svc.name}=${svc.state}:${svc.port}
2132
+ `);
2133
+ }
2134
+ }
2135
+ async function handleClean(jsonMode) {
2136
+ const spinner = start("Removing conflicting containers...");
2137
+ try {
2138
+ try {
2139
+ dockerCompose("down");
2140
+ } catch {
2141
+ }
2142
+ const removed = removeConflictingContainers();
2143
+ if (removed.length > 0) {
2144
+ spinner.stop(`Removed ${removed.length} container${removed.length > 1 ? "s" : ""}: ${removed.join(", ")}`);
2145
+ } else {
2146
+ spinner.stop("No conflicting containers found");
2147
+ }
2148
+ if (jsonMode) {
2149
+ writeJsonResult({ subcommand: "clean", status: "cleaned", removed });
2150
+ return;
2151
+ }
2152
+ } catch (err) {
2153
+ spinner.stop(red("Failed to clean up"));
2154
+ throw err;
2155
+ }
2156
+ }
2157
+ async function handleLogs() {
2158
+ const composePath = getComposePath();
2159
+ const child = spawn("docker", ["compose", "-f", composePath, "logs", "-f"], {
2160
+ stdio: "inherit"
2161
+ });
2162
+ return new Promise((resolve4, reject) => {
2163
+ child.on("close", (code) => {
2164
+ if (code === 0 || code === 130 || code === null) {
2165
+ resolve4();
2166
+ } else {
2167
+ reject(new Error(`docker compose logs exited with code ${code}`));
2168
+ }
2169
+ });
2170
+ child.on("error", reject);
2171
+ });
2172
+ }
2173
+ async function localnetCommand(args) {
2174
+ const subcommand = args.subcommand;
2175
+ if (!subcommand || !isValidSubcommand(subcommand)) {
2176
+ throw new Error(`Usage: midnight localnet <${VALID_SUBCOMMANDS.join("|")}>
2177
+
2178
+ ` + `Subcommands:
2179
+ ` + ` up Start the local network
2180
+ ` + ` stop Stop containers (preserves state)
2181
+ ` + ` down Remove containers, networks, volumes
2182
+ ` + ` status Show service status
2183
+ ` + ` logs Stream service logs
2184
+ ` + ` clean Remove conflicting containers
2185
+
2186
+ ` + `Example: midnight localnet up`);
2187
+ }
2188
+ checkDockerAvailable();
2189
+ const jsonMode = hasFlag(args, "json");
2190
+ process.stderr.write(`
2191
+ ` + header("Localnet") + `
2192
+
2193
+ `);
2194
+ switch (subcommand) {
2195
+ case "up":
2196
+ return handleUp(jsonMode);
2197
+ case "stop":
2198
+ return handleStop(jsonMode);
2199
+ case "down":
2200
+ return handleDown(jsonMode);
2201
+ case "status":
2202
+ return handleStatus(jsonMode);
2203
+ case "logs":
2204
+ return handleLogs();
2205
+ case "clean":
2206
+ return handleClean(jsonMode);
2207
+ }
2208
+ }
2209
+ var VALID_SUBCOMMANDS;
2210
+ var init_localnet2 = __esm(() => {
2211
+ init_localnet();
2212
+ init_format();
2213
+ init_spinner();
2214
+ VALID_SUBCOMMANDS = ["up", "stop", "down", "status", "logs", "clean"];
2215
+ });
2216
+
2217
+ // src/mcp-server.ts
2218
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2219
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
2220
+ import { ListToolsRequestSchema, CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
2221
+ import { createRequire } from "node:module";
2222
+
2223
+ // src/lib/run-command.ts
2224
+ async function captureCommand(handler, args, signal) {
2225
+ const chunks = [];
2226
+ setCaptureTarget((json) => chunks.push(json));
2227
+ const originalStderr = process.stderr.write;
2228
+ process.stderr.write = () => true;
2229
+ try {
2230
+ args.flags.json = true;
2231
+ await handler(args, signal);
2232
+ const raw = chunks.join("").trim();
2233
+ if (!raw)
2234
+ return {};
2235
+ return JSON.parse(raw);
2236
+ } finally {
2237
+ setCaptureTarget(null);
2238
+ process.stderr.write = originalStderr;
2239
+ }
2240
+ }
2241
+
2242
+ // src/lib/exit-codes.ts
2243
+ var EXIT_GENERAL_ERROR = 1;
2244
+ var EXIT_INVALID_ARGS = 2;
2245
+ var EXIT_WALLET_NOT_FOUND = 3;
2246
+ var EXIT_NETWORK_ERROR = 4;
2247
+ var EXIT_INSUFFICIENT_BALANCE = 5;
2248
+ var EXIT_TX_REJECTED = 6;
2249
+ var EXIT_CANCELLED = 7;
2250
+ var ERROR_CODES = {
2251
+ INVALID_ARGS: "INVALID_ARGS",
2252
+ WALLET_NOT_FOUND: "WALLET_NOT_FOUND",
2253
+ NETWORK_ERROR: "NETWORK_ERROR",
2254
+ INSUFFICIENT_BALANCE: "INSUFFICIENT_BALANCE",
2255
+ TX_REJECTED: "TX_REJECTED",
2256
+ STALE_UTXO: "STALE_UTXO",
2257
+ PROOF_TIMEOUT: "PROOF_TIMEOUT",
2258
+ DUST_REQUIRED: "DUST_REQUIRED",
2259
+ CANCELLED: "CANCELLED",
2260
+ UNKNOWN: "UNKNOWN"
2261
+ };
2262
+ function classifyError(err) {
2263
+ const msg = (err.message ?? "").toLowerCase();
2264
+ if (msg.includes("operation cancelled") || msg.includes("operation aborted") || msg === "cancelled" || msg === "aborted") {
2265
+ return { exitCode: EXIT_CANCELLED, errorCode: ERROR_CODES.CANCELLED };
2266
+ }
2267
+ if (msg.includes("wallet file not found") || msg.includes("wallet") && msg.includes("not found")) {
2268
+ return { exitCode: EXIT_WALLET_NOT_FOUND, errorCode: ERROR_CODES.WALLET_NOT_FOUND };
2269
+ }
2270
+ 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:")) {
2271
+ return { exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.INVALID_ARGS };
2272
+ }
2273
+ if (msg.includes("proof") && msg.includes("timeout")) {
2274
+ return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.PROOF_TIMEOUT };
2275
+ }
2276
+ if (msg.includes("stale utxo") || msg.includes("error code 115") || msg.includes("errorcode: 115")) {
2277
+ return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.STALE_UTXO };
2278
+ }
2279
+ if (msg.includes("no dust") || msg.includes("dust") && (msg.includes("required") || msg.includes("available") || msg.includes("insufficient"))) {
2280
+ return { exitCode: EXIT_INSUFFICIENT_BALANCE, errorCode: ERROR_CODES.DUST_REQUIRED };
2281
+ }
2282
+ if (msg.includes("insufficient") || msg.includes("not enough")) {
2283
+ return { exitCode: EXIT_INSUFFICIENT_BALANCE, errorCode: ERROR_CODES.INSUFFICIENT_BALANCE };
2284
+ }
2285
+ if (msg.includes("rejected") || msg.includes("transaction failed")) {
2286
+ return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.TX_REJECTED };
2287
+ }
2288
+ if (msg.includes("econnrefused") || msg.includes("enotfound") || msg.includes("etimedout") || msg.includes("websocket") || msg.includes("connection refused") || msg.includes("network") && msg.includes("error")) {
2289
+ return { exitCode: EXIT_NETWORK_ERROR, errorCode: ERROR_CODES.NETWORK_ERROR };
2290
+ }
2291
+ return { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.UNKNOWN };
2292
+ }
2293
+
2294
+ // src/mcp-server.ts
2295
+ var require2 = createRequire(import.meta.url);
2296
+ var pkg = require2("../package.json");
2297
+ function buildArgs(command, params, subcommand) {
2298
+ const flags = { json: true };
2299
+ const positionals = [];
2300
+ for (const [key, value] of Object.entries(params)) {
2301
+ if (value === undefined || value === null)
2302
+ continue;
2303
+ if (typeof value === "boolean") {
2304
+ if (value)
2305
+ flags[key] = true;
2306
+ } else {
2307
+ flags[key] = String(value);
2308
+ }
2309
+ }
2310
+ return {
2311
+ command,
2312
+ subcommand,
2313
+ positionals,
2314
+ flags
2315
+ };
2316
+ }
2317
+ var handlerLoaders = {
2318
+ generate: () => Promise.resolve().then(() => (init_generate(), exports_generate)),
2319
+ info: () => Promise.resolve().then(() => (init_info(), exports_info)),
2320
+ balance: () => Promise.resolve().then(() => (init_balance(), exports_balance)),
2321
+ address: () => Promise.resolve().then(() => (init_address(), exports_address)),
2322
+ "genesis-address": () => Promise.resolve().then(() => (init_genesis_address(), exports_genesis_address)),
2323
+ "inspect-cost": () => Promise.resolve().then(() => (init_inspect_cost(), exports_inspect_cost)),
2324
+ airdrop: () => Promise.resolve().then(() => (init_airdrop(), exports_airdrop)),
2325
+ transfer: () => Promise.resolve().then(() => (init_transfer2(), exports_transfer)),
2326
+ dust: () => Promise.resolve().then(() => (init_dust(), exports_dust)),
2327
+ config: () => Promise.resolve().then(() => (init_config(), exports_config)),
2328
+ localnet: () => Promise.resolve().then(() => (init_localnet2(), exports_localnet))
2329
+ };
2330
+ async function importHandler(name) {
2331
+ const loader = handlerLoaders[name];
2332
+ if (!loader)
2333
+ throw new Error(`Unknown command handler: ${name}`);
2334
+ const mod = await loader();
2335
+ return mod.default;
2336
+ }
2337
+ var TOOLS = [
2338
+ {
2339
+ name: "midnight_generate",
2340
+ description: "Generate a new wallet (random mnemonic, or restore from seed/mnemonic)",
2341
+ inputSchema: {
2342
+ type: "object",
2343
+ properties: {
2344
+ network: { type: "string", description: "Network: preprod, preview, undeployed", enum: ["preprod", "preview", "undeployed"] },
2345
+ seed: { type: "string", description: "Restore from existing seed (64-char hex)" },
2346
+ mnemonic: { type: "string", description: "Restore from BIP-39 mnemonic (24 words)" },
2347
+ output: { type: "string", description: "Custom output path (default: ~/.midnight/wallet.json)" },
2348
+ force: { type: "string", description: 'Set to "true" to overwrite existing wallet file' }
2349
+ }
2350
+ },
2351
+ async handler(params) {
2352
+ const args = buildArgs("generate", params);
2353
+ if (params.force === "true" || params.force === true)
2354
+ args.flags.force = true;
2355
+ const handler = await importHandler("generate");
2356
+ return captureCommand(handler, args);
2357
+ }
2358
+ },
2359
+ {
2360
+ name: "midnight_info",
2361
+ description: "Display wallet address, network, creation date (no secrets shown)",
2362
+ inputSchema: {
2363
+ type: "object",
2364
+ properties: {
2365
+ wallet: { type: "string", description: "Custom wallet file path" }
2366
+ }
2367
+ },
2368
+ async handler(params) {
2369
+ const args = buildArgs("info", params);
2370
+ const handler = await importHandler("info");
2371
+ return captureCommand(handler, args);
2372
+ }
2373
+ },
2374
+ {
2375
+ name: "midnight_balance",
2376
+ description: "Check unshielded balance via indexer subscription",
2377
+ inputSchema: {
2378
+ type: "object",
2379
+ properties: {
2380
+ address: { type: "string", description: "Address to check (or reads from wallet file)" },
2381
+ wallet: { type: "string", description: "Custom wallet file path" },
2382
+ network: { type: "string", description: "Override network detection", enum: ["preprod", "preview", "undeployed"] },
2383
+ "indexer-ws": { type: "string", description: "Custom indexer WebSocket URL" }
2384
+ }
2385
+ },
2386
+ async handler(params) {
2387
+ const address = params.address;
2388
+ const args = buildArgs("balance", params, address);
2389
+ delete args.flags.address;
2390
+ const handler = await importHandler("balance");
2391
+ return captureCommand(handler, args);
2392
+ }
2393
+ },
2394
+ {
2395
+ name: "midnight_address",
2396
+ description: "Derive and display an unshielded address from a seed",
2397
+ inputSchema: {
2398
+ type: "object",
2399
+ properties: {
2400
+ seed: { type: "string", description: "Seed to derive from (required, 64-char hex)" },
2401
+ network: { type: "string", description: "Network for address prefix", enum: ["preprod", "preview", "undeployed"] },
2402
+ index: { type: "string", description: "Key derivation index (default: 0)" }
2403
+ },
2404
+ required: ["seed"]
2405
+ },
2406
+ async handler(params) {
2407
+ const args = buildArgs("address", params);
2408
+ const handler = await importHandler("address");
2409
+ return captureCommand(handler, args);
2410
+ }
2411
+ },
2412
+ {
2413
+ name: "midnight_genesis_address",
2414
+ description: "Display the genesis wallet address (seed 0x01) for a network",
2415
+ inputSchema: {
2416
+ type: "object",
2417
+ properties: {
2418
+ network: { type: "string", description: "Network for address prefix", enum: ["preprod", "preview", "undeployed"] }
2419
+ }
2420
+ },
2421
+ async handler(params) {
2422
+ const args = buildArgs("genesis-address", params);
2423
+ const handler = await importHandler("genesis-address");
2424
+ return captureCommand(handler, args);
2425
+ }
2426
+ },
2427
+ {
2428
+ name: "midnight_inspect_cost",
2429
+ description: "Display current block limits derived from LedgerParameters",
2430
+ inputSchema: {
2431
+ type: "object",
2432
+ properties: {}
2433
+ },
2434
+ async handler() {
2435
+ const args = buildArgs("inspect-cost", {});
2436
+ const handler = await importHandler("inspect-cost");
2437
+ return captureCommand(handler, args);
2438
+ }
2439
+ },
2440
+ {
2441
+ name: "midnight_airdrop",
2442
+ description: "Fund your wallet from the genesis wallet (undeployed network only)",
2443
+ inputSchema: {
2444
+ type: "object",
2445
+ properties: {
2446
+ amount: { type: "string", description: "Amount in NIGHT to airdrop" },
2447
+ wallet: { type: "string", description: "Custom wallet file path" }
2448
+ },
2449
+ required: ["amount"]
2450
+ },
2451
+ async handler(params) {
2452
+ const amount = params.amount;
2453
+ const args = buildArgs("airdrop", params, amount);
2454
+ delete args.flags.amount;
2455
+ const handler = await importHandler("airdrop");
2456
+ return captureCommand(handler, args);
2457
+ }
2458
+ },
2459
+ {
2460
+ name: "midnight_transfer",
2461
+ description: "Send NIGHT tokens to another address",
2462
+ inputSchema: {
2463
+ type: "object",
2464
+ properties: {
2465
+ to: { type: "string", description: "Recipient bech32m address" },
2466
+ amount: { type: "string", description: "Amount in NIGHT to send" },
2467
+ wallet: { type: "string", description: "Custom wallet file path" }
2468
+ },
2469
+ required: ["to", "amount"]
2470
+ },
2471
+ async handler(params) {
2472
+ const to = params.to;
2473
+ const amount = params.amount;
2474
+ const args = buildArgs("transfer", params, to);
2475
+ args.positionals = [amount];
2476
+ delete args.flags.to;
2477
+ delete args.flags.amount;
2478
+ const handler = await importHandler("transfer");
2479
+ return captureCommand(handler, args);
2480
+ }
2481
+ },
2482
+ {
2483
+ name: "midnight_dust_register",
2484
+ description: "Register NIGHT UTXOs for dust (fee token) generation",
2485
+ inputSchema: {
2486
+ type: "object",
2487
+ properties: {
2488
+ wallet: { type: "string", description: "Custom wallet file path" }
2489
+ }
2490
+ },
2491
+ async handler(params) {
2492
+ const args = buildArgs("dust", params, "register");
2493
+ const handler = await importHandler("dust");
2494
+ return captureCommand(handler, args);
2495
+ }
2496
+ },
2497
+ {
2498
+ name: "midnight_dust_status",
2499
+ description: "Check dust registration status and balance",
2500
+ inputSchema: {
2501
+ type: "object",
2502
+ properties: {
2503
+ wallet: { type: "string", description: "Custom wallet file path" }
2504
+ }
2505
+ },
2506
+ async handler(params) {
2507
+ const args = buildArgs("dust", params, "status");
2508
+ const handler = await importHandler("dust");
2509
+ return captureCommand(handler, args);
2510
+ }
2511
+ },
2512
+ {
2513
+ name: "midnight_config_get",
2514
+ description: "Read a persistent config value",
2515
+ inputSchema: {
2516
+ type: "object",
2517
+ properties: {
2518
+ key: { type: "string", description: 'Config key to read (e.g. "network")' }
2519
+ },
2520
+ required: ["key"]
2521
+ },
2522
+ async handler(params) {
2523
+ const key = params.key;
2524
+ const args = {
2525
+ command: "config",
2526
+ subcommand: "get",
2527
+ positionals: [key],
2528
+ flags: { json: true }
2529
+ };
2530
+ const handler = await importHandler("config");
2531
+ return captureCommand(handler, args);
2532
+ }
2533
+ },
2534
+ {
2535
+ name: "midnight_config_set",
2536
+ description: "Write a persistent config value",
2537
+ inputSchema: {
2538
+ type: "object",
2539
+ properties: {
2540
+ key: { type: "string", description: 'Config key to set (e.g. "network")' },
2541
+ value: { type: "string", description: "Config value to set" }
2542
+ },
2543
+ required: ["key", "value"]
2544
+ },
2545
+ async handler(params) {
2546
+ const key = params.key;
2547
+ const value = params.value;
2548
+ const args = {
2549
+ command: "config",
2550
+ subcommand: "set",
2551
+ positionals: [key, value],
2552
+ flags: { json: true }
2553
+ };
2554
+ const handler = await importHandler("config");
2555
+ return captureCommand(handler, args);
2556
+ }
2557
+ },
2558
+ {
2559
+ name: "midnight_localnet_up",
2560
+ description: "Start a local Midnight network via Docker Compose",
2561
+ inputSchema: {
2562
+ type: "object",
2563
+ properties: {}
2564
+ },
2565
+ async handler() {
2566
+ const args = {
2567
+ command: "localnet",
2568
+ subcommand: "up",
2569
+ positionals: [],
2570
+ flags: { json: true }
2571
+ };
2572
+ const handler = await importHandler("localnet");
2573
+ return captureCommand(handler, args);
2574
+ }
2575
+ },
2576
+ {
2577
+ name: "midnight_localnet_stop",
2578
+ description: "Stop local network containers (preserves state for fast restart)",
2579
+ inputSchema: {
2580
+ type: "object",
2581
+ properties: {}
2582
+ },
2583
+ async handler() {
2584
+ const args = {
2585
+ command: "localnet",
2586
+ subcommand: "stop",
2587
+ positionals: [],
2588
+ flags: { json: true }
2589
+ };
2590
+ const handler = await importHandler("localnet");
2591
+ return captureCommand(handler, args);
2592
+ }
2593
+ },
2594
+ {
2595
+ name: "midnight_localnet_down",
2596
+ description: "Remove local network containers, networks, and volumes (full teardown)",
2597
+ inputSchema: {
2598
+ type: "object",
2599
+ properties: {}
2600
+ },
2601
+ async handler() {
2602
+ const args = {
2603
+ command: "localnet",
2604
+ subcommand: "down",
2605
+ positionals: [],
2606
+ flags: { json: true }
2607
+ };
2608
+ const handler = await importHandler("localnet");
2609
+ return captureCommand(handler, args);
2610
+ }
2611
+ },
2612
+ {
2613
+ name: "midnight_localnet_status",
2614
+ description: "Show local network service status and ports",
2615
+ inputSchema: {
2616
+ type: "object",
2617
+ properties: {}
2618
+ },
2619
+ async handler() {
2620
+ const args = {
2621
+ command: "localnet",
2622
+ subcommand: "status",
2623
+ positionals: [],
2624
+ flags: { json: true }
2625
+ };
2626
+ const handler = await importHandler("localnet");
2627
+ return captureCommand(handler, args);
2628
+ }
2629
+ },
2630
+ {
2631
+ name: "midnight_localnet_clean",
2632
+ description: "Remove conflicting containers from other setups",
2633
+ inputSchema: {
2634
+ type: "object",
2635
+ properties: {}
2636
+ },
2637
+ async handler() {
2638
+ const args = {
2639
+ command: "localnet",
2640
+ subcommand: "clean",
2641
+ positionals: [],
2642
+ flags: { json: true }
2643
+ };
2644
+ const handler = await importHandler("localnet");
2645
+ return captureCommand(handler, args);
2646
+ }
2647
+ }
2648
+ ];
2649
+ var server = new Server({ name: "midnight-wallet-cli", version: pkg.version }, { capabilities: { tools: {} } });
2650
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
2651
+ return {
2652
+ tools: TOOLS.map((t) => ({
2653
+ name: t.name,
2654
+ description: t.description,
2655
+ inputSchema: t.inputSchema
2656
+ }))
2657
+ };
2658
+ });
2659
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
2660
+ const { name, arguments: params } = request.params;
2661
+ const tool = TOOLS.find((t) => t.name === name);
2662
+ if (!tool) {
2663
+ return {
2664
+ content: [{ type: "text", text: `Unknown tool: ${name}` }],
2665
+ isError: true
2666
+ };
2667
+ }
2668
+ try {
2669
+ const result = await tool.handler(params ?? {});
2670
+ return {
2671
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
2672
+ };
2673
+ } catch (err) {
2674
+ const error = err instanceof Error ? err : new Error(String(err));
2675
+ const { errorCode } = classifyError(error);
2676
+ return {
2677
+ content: [{
2678
+ type: "text",
2679
+ text: JSON.stringify({ error: true, code: errorCode, message: error.message })
2680
+ }],
2681
+ isError: true
2682
+ };
2683
+ }
2684
+ });
2685
+ async function main() {
2686
+ const transport = new StdioServerTransport;
2687
+ await server.connect(transport);
2688
+ }
2689
+ main().catch((err) => {
2690
+ process.stderr.write(`MCP server error: ${err.message}
2691
+ `);
2692
+ process.exit(1);
2693
+ });