midnight-wallet-cli 0.1.7 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/mcp-server.js +217 -2764
  2. package/dist/wallet.js +263 -3573
  3. package/package.json +2 -2
@@ -1,739 +1,47 @@
1
1
  #!/usr/bin/env node
2
- var __defProp = Object.defineProperty;
3
- var __export = (target, all) => {
4
- for (var name in all)
5
- __defProp(target, name, {
6
- get: all[name],
7
- enumerable: true,
8
- configurable: true,
9
- set: (newValue) => all[name] = () => newValue
10
- });
11
- };
12
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
13
-
14
- // src/lib/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, DUST_REGISTRATION_TIMEOUT_MS = 600000, DUST_REGISTRATION_RETRY_DELAY_MS = 15000, STALE_UTXO_ERROR_CODE = 115, MIDNIGHT_DIR = ".midnight", DEFAULT_WALLET_FILENAME = "wallet.json", DEFAULT_CONFIG_FILENAME = "config.json", DIR_MODE = 448, FILE_MODE = 384, LOCALNET_DIR_NAME = "localnet";
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 = `
2
+ var m3=Object.defineProperty;var C=($,Z)=>{for(var Q in Z)m3($,Q,{get:Z[Q],enumerable:!0,configurable:!0,set:(X)=>Z[Q]=()=>X})};var M=($,Z)=>()=>($&&(Z=$($=0)),Z);function u0($){m0=$}function F($){let Z=JSON.stringify($)+`
3
+ `;if(m0)m0(Z);else process.stdout.write(Z)}var m0=null;function _($,Z){let Q=$.flags[Z];if(Q===void 0||Q===!0)return;return Q}function L($,Z){return Z in $.flags}function B1($,Z,Q){let X=_($,Z);if(X===void 0)throw new Error(`Missing required flag: --${Z} <${Q}>`);return X}import{HDWallet as g3,Roles as l3}from"@midnight-ntwrk/wallet-sdk-hd";import{createKeystore as d3,PublicKey as i3}from"@midnight-ntwrk/wallet-sdk-unshielded-wallet";import{NetworkId as g0}from"@midnight-ntwrk/wallet-sdk-abstractions";function Q0($,Z,Q=0){let X=o3[Z],z=g3.fromSeed($);if(z.type!=="seedOk")throw new Error("Invalid seed for HD wallet");let q=z.hdWallet.selectAccount(0).selectRole(l3.NightExternal).deriveKeyAt(Q);if(q.type==="keyOutOfBounds")throw new Error(`Key index ${Q} out of bounds`);let Y=d3(q.key,X);return i3.fromKeyStore(Y).address}var o3;var P0=M(()=>{o3={preprod:g0.NetworkId.PreProd,preview:g0.NetworkId.Preview,undeployed:g0.NetworkId.Undeployed}});import{execSync as n3}from"child_process";function l($){return H1.includes($)}function t3($){return{...a3[$]}}function W1(){return H1}function V1($){if($.startsWith("mn_addr_preprod1"))return"preprod";if($.startsWith("mn_addr_preview1"))return"preview";if($.startsWith("mn_addr_undeployed1"))return"undeployed";return null}function r3(){try{let $=n3('docker ps --format "{{.Image}}|{{.Ports}}"',{encoding:"utf-8",timeout:5000}),Z={};for(let Q of $.trim().split(`
4
+ `)){if(!Q)continue;let[X,z]=Q.split("|"),q=(Y)=>{let K=new RegExp(`0\\.0\\.0\\.0:(\\d+)->${Y}/tcp`),J=z?.match(K);return J?parseInt(J[1],10):void 0};if(X.includes("indexer-standalone")||X.includes("indexer")){let Y=q(8088);if(Y)Z.indexerPort=Y}if(X.includes("midnight-node")){let Y=q(9944);if(Y)Z.nodePort=Y}if(X.includes("proof-server")){let Y=q(6300);if(Y)Z.proofServerPort=Y}}return Z}catch{return{}}}function F1($){let Z=t3($);if($==="undeployed"){let Q=r3();if(Q.indexerPort)Z.indexer=`http://localhost:${Q.indexerPort}/api/v3/graphql`,Z.indexerWS=`ws://localhost:${Q.indexerPort}/api/v3/graphql/ws`;if(Q.nodePort)Z.node=`ws://localhost:${Q.nodePort}`;if(Q.proofServerPort)Z.proofServer=`http://localhost:${Q.proofServerPort}`}return Z}var a3,H1;var M0=M(()=>{a3={preprod:{indexer:"https://indexer.preprod.midnight.network/api/v3/graphql",indexerWS:"wss://indexer.preprod.midnight.network/api/v3/graphql/ws",node:"wss://rpc.preprod.midnight.network",proofServer:"http://localhost:6300",networkId:"PreProd"},preview:{indexer:"https://indexer.preview.midnight.network/api/v3/graphql",indexerWS:"wss://indexer.preview.midnight.network/api/v3/graphql/ws",node:"wss://rpc.preview.midnight.network",proofServer:"http://localhost:6300",networkId:"Preview"},undeployed:{indexer:"http://localhost:8088/api/v3/graphql",indexerWS:"ws://localhost:8088/api/v3/graphql/ws",node:"ws://localhost:9944",proofServer:"http://localhost:6300",networkId:"Undeployed"}},H1=["preprod","preview","undeployed"]});var O0="0000000000000000000000000000000000000000000000000000000000000001",L1="0000000000000000000000000000000000000000000000000000000000000000",l0=6,P1=1e6,M1=1000000000000n,O1=5,_1=300000,y1=1e4,_0=120000,A1=300000,d0=60000,i0=10,y0=3,I1=600000,A0=15000,T1=115,p=".midnight",X0="wallet.json",R1="config.json",r=448,I0=384,D1="localnet";import*as d from"fs";import*as o0 from"path";import{homedir as s3}from"os";function E1($){return $??o0.join(s3(),p)}function x1($){return o0.join(E1($),R1)}function e3($){let Z=E1($);if(!d.existsSync(Z))d.mkdirSync(Z,{recursive:!0,mode:r})}function R0($){let Z=x1($);if(!d.existsSync(Z))return{...T0};let Q;try{Q=d.readFileSync(Z,"utf-8")}catch{return{...T0}}let X;try{X=JSON.parse(Q)}catch{return{...T0}}return{network:X.network&&l(X.network)?X.network:T0.network}}function $2($,Z){e3(Z);let Q=x1(Z);d.writeFileSync(Q,JSON.stringify($,null,2)+`
5
+ `,{mode:I0})}function N1($,Z){let Q=R0(Z);if($==="network")return Q.network;throw new Error(`Unknown config key: "${$}"
6
+ Valid keys: ${n0.join(", ")}`)}function C1($,Z,Q){let X=R0(Q);if($==="network"){if(!l(Z))throw new Error(`Invalid network: "${Z}"
7
+ Valid networks: preprod, preview, undeployed`);X.network=Z}else throw new Error(`Unknown config key: "${$}"
8
+ Valid keys: ${n0.join(", ")}`);$2(X,Q)}function a0(){return n0}var T0,n0;var t0=M(()=>{M0();T0={network:"undeployed"},n0=["network"]});function s($){let Z=_($.args,"network");if(Z!==void 0){if(!l(Z))throw new Error(`Invalid network: "${Z}"
9
+ Valid networks: ${W1().join(", ")}`);return Z}if($.walletNetwork&&l($.walletNetwork))return $.walletNetwork;if($.address){let X=V1($.address);if(X)return X}let Q=R0($.configDir);if(Q.network&&l(Q.network))return Q.network;return"undeployed"}function i($){let Z=s($),Q=F1(Z);return{name:Z,config:Q}}var o=M(()=>{M0();t0()});import*as v from"fs";import*as n from"path";import{homedir as Z2}from"os";function v1(){return n.join(Z2(),p)}function w1(){return n.join(v1(),X0)}function Q2(){let $=v1();if(!v.existsSync($))v.mkdirSync($,{recursive:!0,mode:r})}function c($){let Z=$?n.resolve($):w1();if(!v.existsSync(Z))throw new Error(`Wallet file not found: ${Z}
10
+ Generate a wallet first: midnight generate --network <name>`);let Q;try{Q=v.readFileSync(Z,"utf-8")}catch(z){throw new Error(`Failed to read wallet file: ${Z}
11
+ ${z.message}`)}let X;try{X=JSON.parse(Q)}catch{throw new Error(`Invalid JSON in wallet file: ${Z}`)}if(!X.seed||!X.network||!X.address||!X.createdAt){let z=["seed","network","address","createdAt"].filter((q)=>!X[q]);throw new Error(`Wallet file is missing required fields (${z.join(", ")}): ${Z}`)}if(!/^[0-9a-fA-F]+$/.test(X.seed))throw new Error(`Invalid seed format in wallet file (expected hex string): ${Z}`);if(!l(X.network))throw new Error(`Invalid network "${X.network}" in wallet file: ${Z}
12
+ Valid networks: preprod, preview, undeployed`);return X}function b1($,Z){let Q=Z?n.resolve(Z):w1();if(!Z)Q2();else{let X=n.dirname(Q);if(!v.existsSync(X))v.mkdirSync(X,{recursive:!0,mode:r})}return v.writeFileSync(Q,JSON.stringify($,null,2)+`
13
+ `,{mode:I0}),Q}var e=M(()=>{M0()});function z0(){return!("NO_COLOR"in process.env)}function J0($,Z){if(!z0())return $;return`\x1B[38;5;${Z}m${$}\x1B[0m`}function O($){if(!z0())return $;return`\x1B[1m${$}\x1B[0m`}function V($){if(!z0())return $;return`\x1B[2m${$}\x1B[0m`}function K0($){return J0($,38)}function $0($){return J0($,196)}function a($){return J0($,40)}function U0($){return J0($,226)}function S1($){return J0($,245)}function A($,Z=h1){let Q=` ${$} `,X=Z-Q.length;if(X<=0)return O(Q);let z=Math.floor(X/2),q=X-z;return O("═".repeat(z)+Q+"═".repeat(q))}function y($=h1){return V("─".repeat($))}function j($,Z,Q=16){let X=($+":").padEnd(Q);return` ${S1(X)}${Z}`}function j0($){let Z=$<0n,Q=Z?-$:$,X=BigInt(10**l0),z=Q/X,Y=(Q%X).toString().padStart(l0,"0");return`${Z?"-":""}${z}.${Y}`}function D0($){return`${j0($)} NIGHT`}function B0($){let Z=$<0n,Q=Z?-$:$,X=10n**BigInt(k1),z=Q/X,K=(Q%X).toString().padStart(k1,"0").replace(/0+$/,"").padEnd(6,"0");return`${Z?"-":""}${z}.${K}`}function E0($){return`${B0($)} DUST`}function R($,Z=!1){let Q=Z&&$.length>20?$.slice(0,10)+"…"+$.slice(-8):$;return K0(Q)}function Z0($,Z){let X=[`${a("✓")} ${$}`];if(Z)X.push(j("Transaction",K0(Z)));return X.join(`
14
+ `)}var h1=60,k1=15;var N=()=>{};var u1={};C(u1,{default:()=>m1});import*as c1 from"fs";import*as x0 from"path";import{homedir as X2}from"os";import{generateMnemonic as z2,mnemonicToSeedSync as f1,validateMnemonic as q2}from"@scure/bip39";import{wordlist as p1}from"@scure/bip39/wordlists/english.js";async function m1($){let Z=s({args:$}),Q=_($,"output"),X=_($,"seed"),z=_($,"mnemonic");if(X!==void 0&&z!==void 0)throw new Error("Cannot specify both --seed and --mnemonic. Use one or the other.");let q=Q?x0.resolve(Q):x0.join(X2(),p,X0);if(c1.existsSync(q)&&!L($,"force"))throw new Error(`Wallet file already exists: ${q}
15
+ Use --force to overwrite, or --output <file> to save to a different path.`);let Y,K;if(X!==void 0){let G=X.replace(/^0x/,"");if(G.length!==64||!/^[0-9a-fA-F]+$/.test(G))throw new Error("Seed must be a 64-character hex string (32 bytes)");Y=Buffer.from(G,"hex")}else if(z!==void 0){if(!q2(z,p1))throw new Error("Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.");K=z,Y=Buffer.from(f1(K).slice(0,32))}else K=z2(p1,256),Y=Buffer.from(f1(K).slice(0,32));let J=Q0(Y,Z),B={seed:Y.toString("hex"),network:Z,address:J,createdAt:new Date().toISOString()};if(K)B.mnemonic=K;let U=b1(B,Q);if(L($,"json")){let G={address:J,network:Z,seed:Y.toString("hex"),file:U,createdAt:B.createdAt};if(K)G.mnemonic=K;F(G);return}if(process.stdout.write(J+`
16
+ `),process.stderr.write(`
17
+ `+A("Wallet Generated")+`
18
+
19
+ `),process.stderr.write(j("Network",Z)+`
20
+ `),process.stderr.write(j("Address",R(J))+`
21
+ `),process.stderr.write(j("File",U)+`
22
+ `),process.stderr.write(`
23
+ `),K)process.stderr.write(U0(O(" MNEMONIC (save securely!):"))+`
24
+ `),process.stderr.write(` ${K}
25
+
26
+ `);process.stderr.write(U0(O(" SEED (hex):"))+`
27
+ `),process.stderr.write(` ${Y.toString("hex")}
28
+
29
+ `),process.stderr.write(y()+`
30
+ `),process.stderr.write(V(" Next: midnight info | midnight balance")+`
31
+
32
+ `),process.stderr.write(a("✓")+` Wallet saved
33
+ `)}var g1=M(()=>{P0();o();e();N()});var d1={};C(d1,{default:()=>l1});import*as N0 from"path";import{homedir as Y2}from"os";async function l1($){let Z=_($,"wallet"),Q=c(Z),X=Z?N0.resolve(Z):N0.join(Y2(),p,X0);if(L($,"json")){F({address:Q.address,network:Q.network,createdAt:Q.createdAt,file:X});return}process.stdout.write(Q.address+`
34
+ `),process.stderr.write(`
35
+ `+A("Wallet Info")+`
36
+
37
+ `),process.stderr.write(j("Address",R(Q.address))+`
38
+ `),process.stderr.write(j("Network",Q.network)+`
39
+ `),process.stderr.write(j("Created",Q.createdAt)+`
40
+ `),process.stderr.write(j("File",X)+`
41
+ `),process.stderr.write(`
42
+ `+y()+`
43
+
44
+ `)}var i1=M(()=>{e();N();N()});import G2 from"ws";function o1($,Z,Q){return new Promise((X,z)=>{let q=new G2(Z,["graphql-transport-ws"]),Y=new Map,K=0,J=0,B=0,U=!1,G=!1,H,W=()=>{let k=new Map,h=0;for(let E of Y.values())if(!E.spent){h++;let u=k.get(E.tokenType)??0n;k.set(E.tokenType,u+E.value)}return{balances:k,utxoCount:h,txCount:K,highestTxId:J}},P=()=>{clearTimeout(H)},S=()=>{if(!G&&U&&(J===0||B>=J))G=!0,P(),q.send(JSON.stringify({id:"1",type:"complete"})),q.close(),X(W())};q.on("open",()=>{q.send(JSON.stringify({type:"connection_init"}))}),q.on("message",(k)=>{let h=JSON.parse(k.toString());switch(h.type){case"connection_ack":q.send(JSON.stringify({id:"1",type:"subscribe",payload:{query:J2,variables:{address:$}}}));break;case"next":{if(h.payload?.errors){let u=h.payload.errors[0]?.message||"Unknown GraphQL error";if(!G)G=!0,P(),q.close(),z(new Error(`GraphQL error: ${u}`));return}let E=h.payload?.data?.unshieldedTransactions;if(!E)return;if(E.__typename==="UnshieldedTransaction"){K++;let u=E;B=Math.max(B,u.transaction.id);for(let g of u.createdUtxos){let c0=`${g.intentHash}:${g.outputIndex}`;Y.set(c0,{value:BigInt(g.value),tokenType:g.tokenType,spent:!1})}for(let g of u.spentUtxos){let c0=`${g.intentHash}:${g.outputIndex}`,K1=Y.get(c0);if(K1)K1.spent=!0}if(Q)Q(B,J);S()}else if(E.__typename==="UnshieldedTransactionsProgress")J=E.highestTransactionId,U=!0,S();break}case"error":if(!G)G=!0,P(),q.close(),z(new Error(`GraphQL subscription error: ${JSON.stringify(h.payload)}`));break;case"complete":break}}),q.on("error",(k)=>{if(!G)G=!0,P(),z(new Error(`WebSocket connection failed: ${k.message}`))}),q.on("close",()=>{if(!G)G=!0,P(),z(new Error(`Indexer closed the connection before balance sync completed. Indexer: ${Z}`))}),H=setTimeout(()=>{if(!G)G=!0,q.close(),z(new Error(`Balance check timed out after ${d0/1000}s. Indexer: ${Z}`))},d0)})}function H0($){return $===L1}var J2=`
737
45
  subscription UnshieldedTransactions($address: UnshieldedAddress!) {
738
46
  unshieldedTransactions(address: $address) {
739
47
  __typename
@@ -747,1268 +55,138 @@ var SUBSCRIPTION_QUERY = `
747
55
  }
748
56
  }
749
57
  }
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
- function isTransactionRejectedError(err) {
1247
- let current = err;
1248
- while (current) {
1249
- const msg = String(current?.message ?? "").toLowerCase();
1250
- if (msg.includes("submission error"))
1251
- return true;
1252
- if (msg.includes("transaction") && msg.includes("invalid"))
1253
- return true;
1254
- if (msg.includes("138"))
1255
- return true;
1256
- const tag = current?._tag;
1257
- if (tag === "TransactionInvalidError" || tag === "SubmissionError")
1258
- return true;
1259
- current = current.cause;
1260
- }
1261
- return false;
1262
- }
1263
- function formatElapsed(ms) {
1264
- const totalSeconds = Math.round(ms / 1000);
1265
- if (totalSeconds < 60)
1266
- return `${totalSeconds}s`;
1267
- const minutes = Math.floor(totalSeconds / 60);
1268
- const seconds = totalSeconds % 60;
1269
- return `${minutes}m ${seconds}s`;
1270
- }
1271
- async function submitDustRegistration(bundle, dustUtxos, dustReceiverAddress) {
1272
- const ttl = new Date(Date.now() + TX_TTL_MINUTES * 60 * 1000);
1273
- await bundle.facade.dust.waitForSyncedState();
1274
- const unprovenTx = await bundle.facade.dust.createDustGenerationTransaction(new Date, ttl, dustUtxos, bundle.keystore.getPublicKey(), dustReceiverAddress);
1275
- const intent = unprovenTx.intents?.get(1);
1276
- if (!intent) {
1277
- throw new Error("Dust generation intent not found on transaction");
1278
- }
1279
- const signature = bundle.keystore.signData(intent.signatureData(1));
1280
- const signedTx = await bundle.facade.dust.addDustGenerationSignature(unprovenTx, signature);
1281
- const finalized = await bundle.facade.finalizeTransaction(signedTx);
1282
- return await bundle.facade.submitTransaction(finalized);
1283
- }
1284
- async function registerNightUtxos(bundle, dustUtxos, dustReceiverAddress, onStatus) {
1285
- const startTime = Date.now();
1286
- const deadline = startTime + DUST_REGISTRATION_TIMEOUT_MS;
1287
- let lastError;
1288
- const originalWarn = console.warn;
1289
- const originalError = console.error;
1290
- const hasRpcNoise = (args) => args.some((a) => String(a).includes("RPC-CORE"));
1291
- const suppressRpcNoise = () => {
1292
- console.warn = (...args) => {
1293
- if (hasRpcNoise(args))
1294
- return;
1295
- originalWarn(...args);
1296
- };
1297
- console.error = (...args) => {
1298
- if (hasRpcNoise(args))
1299
- return;
1300
- originalError(...args);
1301
- };
1302
- };
1303
- const restoreConsole = () => {
1304
- console.warn = originalWarn;
1305
- console.error = originalError;
1306
- };
1307
- suppressRpcNoise();
1308
- try {
1309
- while (Date.now() < deadline) {
1310
- try {
1311
- return await submitDustRegistration(bundle, dustUtxos, dustReceiverAddress);
1312
- } catch (err) {
1313
- lastError = err;
1314
- if (isTransactionRejectedError(err) && Date.now() + DUST_REGISTRATION_RETRY_DELAY_MS < deadline) {
1315
- const elapsed = formatElapsed(Date.now() - startTime);
1316
- onStatus?.(`Waiting for dust generation capacity (${elapsed} elapsed, ~5 min on fresh wallets)...`);
1317
- await new Promise((resolve4) => setTimeout(resolve4, DUST_REGISTRATION_RETRY_DELAY_MS));
1318
- continue;
1319
- }
1320
- throw err;
1321
- }
1322
- }
1323
- throw lastError ?? new Error("Dust registration timed out");
1324
- } finally {
1325
- restoreConsole();
1326
- }
1327
- }
1328
- async function ensureDust(bundle, onDust) {
1329
- const state = await rx2.firstValueFrom(bundle.facade.state().pipe(rx2.filter((s) => s.isSynced)));
1330
- const nightUtxos = state.unshielded.availableCoins.filter((coin) => coin.meta?.registeredForDustGeneration !== true);
1331
- if (nightUtxos.length > 0) {
1332
- onDust?.(`Registering ${nightUtxos.length} UTXO(s) for dust generation...`);
1333
- const dustUtxos = nightUtxos.map((coin) => ({
1334
- ...coin.utxo,
1335
- ctime: new Date(coin.meta.ctime)
1336
- }));
1337
- await registerNightUtxos(bundle, dustUtxos, state.dust.dustAddress, onDust);
1338
- } else if (state.dust.availableCoins.length > 0) {
1339
- onDust?.("Dust available");
1340
- return;
1341
- } else {
1342
- onDust?.("UTXOs already registered, waiting for dust generation...");
1343
- }
1344
- onDust?.("Waiting for dust tokens...");
1345
- 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)));
1346
- onDust?.("Dust available");
1347
- }
1348
- async function buildAndSubmitTransfer(bundle, recipientAddress, amount, onProving, onSubmitting, onDust) {
1349
- let lastError;
1350
- for (let attempt = 1;attempt <= MAX_RETRY_ATTEMPTS; attempt++) {
1351
- try {
1352
- if (attempt > 1) {
1353
- await quickSync(bundle);
1354
- }
1355
- const ttl = new Date(Date.now() + TX_TTL_MINUTES * 60 * 1000);
1356
- const unprovenRecipe = await bundle.facade.transferTransaction([
1357
- {
1358
- type: "unshielded",
1359
- outputs: [
1360
- {
1361
- amount,
1362
- receiverAddress: recipientAddress,
1363
- type: ledger3.unshieldedToken().raw
1364
- }
1365
- ]
1366
- }
1367
- ], { shieldedSecretKeys: bundle.zswapSecretKeys, dustSecretKey: bundle.dustSecretKey }, { ttl, payFees: true });
1368
- const signedRecipe = await bundle.facade.signRecipe(unprovenRecipe, (payload) => bundle.keystore.signData(payload));
1369
- onProving?.();
1370
- const finalizedTx = await Promise.race([
1371
- bundle.facade.finalizeRecipe(signedRecipe),
1372
- new Promise((_, reject) => {
1373
- setTimeout(() => reject(new Error("ZK proof generation timed out")), PROOF_TIMEOUT_MS);
1374
- })
1375
- ]);
1376
- onSubmitting?.();
1377
- const txHash = await bundle.facade.submitTransaction(finalizedTx);
1378
- return txHash;
1379
- } catch (err) {
1380
- lastError = err;
1381
- const isStaleUtxo = err?.code === STALE_UTXO_ERROR_CODE || err?.message?.includes("115") || err?.message?.toLowerCase().includes("stale");
1382
- if (isStaleUtxo && attempt < MAX_RETRY_ATTEMPTS) {
1383
- continue;
1384
- }
1385
- const isDustInsufficient = err?.message?.toLowerCase().includes("not enough dust") || err?.message?.toLowerCase().includes("dust generated");
1386
- if (isDustInsufficient && attempt < MAX_RETRY_ATTEMPTS) {
1387
- onDust?.("Waiting for more dust to accumulate...");
1388
- await new Promise((resolve4) => setTimeout(resolve4, DUST_REGISTRATION_RETRY_DELAY_MS));
1389
- continue;
1390
- }
1391
- throw err;
1392
- }
1393
- }
1394
- throw lastError ?? new Error("Transfer failed after retries");
1395
- }
1396
- async function executeTransfer(params) {
1397
- const {
1398
- seedBuffer,
1399
- networkConfig,
1400
- recipientAddress,
1401
- amountNight,
1402
- signal,
1403
- onSync,
1404
- onDust,
1405
- onProving,
1406
- onSubmitting,
1407
- onSyncWarning
1408
- } = params;
1409
- const amount = nightToMicro(amountNight);
1410
- validateRecipientAddress(recipientAddress, networkConfig);
1411
- const unsuppress = suppressSdkTransientErrors(onSyncWarning);
1412
- const bundle = buildFacade(seedBuffer, networkConfig);
1413
- let shutdownComplete = false;
1414
- const cleanup = async () => {
1415
- if (!shutdownComplete) {
1416
- shutdownComplete = true;
1417
- try {
1418
- await stopFacade(bundle);
1419
- } catch {
1420
- }
1421
- }
1422
- };
1423
- const onAbort = () => {
1424
- cleanup();
1425
- };
1426
- signal?.addEventListener("abort", onAbort, { once: true });
1427
- try {
1428
- const syncedState = await startAndSyncFacade(bundle, onSync);
1429
- if (signal?.aborted)
1430
- throw new Error("Operation cancelled");
1431
- const unshieldedBalance = syncedState.unshielded.balances[ledger3.unshieldedToken().raw] ?? 0n;
1432
- if (unshieldedBalance < amount) {
1433
- const haveNight = Number(unshieldedBalance) / TOKEN_MULTIPLIER;
1434
- throw new Error(`Insufficient balance: ${haveNight.toFixed(6)} NIGHT available, ` + `${amountNight} NIGHT requested`);
1435
- }
1436
- if (signal?.aborted)
1437
- throw new Error("Operation cancelled");
1438
- await ensureDust(bundle, onDust);
1439
- if (signal?.aborted)
1440
- throw new Error("Operation cancelled");
1441
- const txHash = await buildAndSubmitTransfer(bundle, recipientAddress, amount, onProving, onSubmitting, onDust);
1442
- return { txHash, amountMicroNight: amount };
1443
- } finally {
1444
- signal?.removeEventListener("abort", onAbort);
1445
- unsuppress();
1446
- await cleanup();
1447
- }
1448
- }
1449
- var NETWORK_ID_MAP3;
1450
- var init_transfer = __esm(() => {
1451
- init_facade();
1452
- NETWORK_ID_MAP3 = {
1453
- PreProd: NetworkId3.NetworkId.PreProd,
1454
- Preview: NetworkId3.NetworkId.Preview,
1455
- Undeployed: NetworkId3.NetworkId.Undeployed
1456
- };
1457
- });
1458
-
1459
- // src/commands/airdrop.ts
1460
- var exports_airdrop = {};
1461
- __export(exports_airdrop, {
1462
- default: () => airdropCommand
1463
- });
1464
- async function airdropCommand(args, signal) {
1465
- const amountStr = args.subcommand;
1466
- if (!amountStr) {
1467
- throw new Error(`Missing amount.
1468
- ` + `Usage: midnight airdrop <amount>
1469
- ` + "Example: midnight airdrop 1000");
1470
- }
1471
- const amountNight = parseAmount(amountStr);
1472
- const walletPath = getFlag(args, "wallet");
1473
- const config = loadWalletConfig(walletPath);
1474
- const { name: networkName, config: networkConfig } = resolveNetwork({
1475
- args,
1476
- walletNetwork: config.network,
1477
- address: config.address
1478
- });
1479
- if (networkName !== "undeployed") {
1480
- throw new Error(`Airdrop is only available on the "undeployed" network (local devnet).
1481
- ` + `Current network: "${networkName}"
1482
- ` + `On preprod/preview, use a faucet or transfer from another wallet.`);
1483
- }
1484
- const recipientAddress = config.address;
1485
- const genesisSeedBuffer = Buffer.from(GENESIS_SEED, "hex");
1486
- process.stderr.write(`
1487
- ` + header("Airdrop") + `
1488
-
1489
- `);
1490
- process.stderr.write(keyValue("Network", networkName) + `
1491
- `);
1492
- process.stderr.write(keyValue("From", dim("genesis (seed 0x01)")) + `
1493
- `);
1494
- process.stderr.write(keyValue("To", formatAddress(recipientAddress, true)) + `
1495
- `);
1496
- process.stderr.write(keyValue("Amount", bold(amountNight + " NIGHT")) + `
1497
- `);
1498
- process.stderr.write(`
1499
- `);
1500
- const spinner = start("Starting genesis wallet...");
1501
- try {
1502
- const result = await executeTransfer({
1503
- seedBuffer: genesisSeedBuffer,
1504
- networkConfig,
1505
- recipientAddress,
1506
- amountNight,
1507
- signal,
1508
- onSync(applied, highest) {
1509
- if (highest > 0) {
1510
- const pct = Math.round(applied / highest * 100);
1511
- spinner.update(`Syncing genesis wallet... ${pct}%`);
1512
- }
1513
- },
1514
- onDust(status) {
1515
- spinner.update(`Dust: ${status}`);
1516
- },
1517
- onProving() {
1518
- spinner.update("Generating ZK proof (this may take a few minutes)...");
1519
- },
1520
- onSubmitting() {
1521
- spinner.update("Submitting transaction...");
1522
- },
1523
- onSyncWarning(_tag, msg) {
1524
- spinner.update(`Syncing genesis wallet... (${msg}, retrying)`);
1525
- }
1526
- });
1527
- spinner.stop("Transaction submitted");
1528
- if (hasFlag(args, "json")) {
1529
- writeJsonResult({
1530
- txHash: result.txHash,
1531
- amount: amountNight,
1532
- recipient: recipientAddress,
1533
- network: networkName
1534
- });
1535
- return;
1536
- }
1537
- process.stdout.write(result.txHash + `
1538
- `);
1539
- process.stderr.write(`
1540
- ` + successMessage(`Airdropped ${amountNight} NIGHT to your wallet`, result.txHash) + `
1541
- `);
1542
- process.stderr.write(`
1543
- ` + divider() + `
1544
- `);
1545
- process.stderr.write(dim(" Verify: midnight balance") + `
1546
- `);
1547
- process.stderr.write(dim(" Register dust: midnight dust register") + `
1548
- `);
1549
- process.stderr.write(dim(" Note: Dust generation takes a few minutes on a fresh wallet.") + `
1550
- `);
1551
- process.stderr.write(dim(" It will happen automatically on your first transfer.") + `
1552
-
1553
- `);
1554
- } catch (err) {
1555
- spinner.stop("Failed");
1556
- if (err instanceof Error && err.message.toLowerCase().includes("dust")) {
1557
- throw new Error(`${err.message}
1558
-
1559
- ` + `On a fresh localnet, the minimum airdrop is ~1 NIGHT.
1560
- ` + `Try: midnight airdrop 1`);
1561
- }
1562
- throw err;
1563
- }
1564
- }
1565
- var init_airdrop = __esm(() => {
1566
- init_wallet_config();
1567
- init_resolve_network();
1568
- init_transfer();
1569
- init_format();
1570
- init_spinner();
1571
- });
1572
-
1573
- // src/commands/transfer.ts
1574
- var exports_transfer = {};
1575
- __export(exports_transfer, {
1576
- default: () => transferCommand
1577
- });
1578
- async function transferCommand(args, signal) {
1579
- const recipientAddress = args.subcommand;
1580
- const amountStr = args.positionals[0];
1581
- if (!recipientAddress) {
1582
- throw new Error(`Missing recipient address.
1583
- ` + `Usage: midnight transfer <to> <amount>
1584
- ` + "Example: midnight transfer mn_addr_undeployed1... 100");
1585
- }
1586
- if (!amountStr) {
1587
- throw new Error(`Missing amount.
1588
- ` + `Usage: midnight transfer <to> <amount>
1589
- ` + "Example: midnight transfer mn_addr_undeployed1... 100");
1590
- }
1591
- const amountNight = parseAmount(amountStr);
1592
- const walletPath = getFlag(args, "wallet");
1593
- const config = loadWalletConfig(walletPath);
1594
- const seedBuffer = Buffer.from(config.seed, "hex");
1595
- const { name: networkName, config: networkConfig } = resolveNetwork({
1596
- args,
1597
- walletNetwork: config.network,
1598
- address: config.address
1599
- });
1600
- process.stderr.write(`
1601
- ` + header("Transfer") + `
1602
-
1603
- `);
1604
- process.stderr.write(keyValue("Network", networkName) + `
1605
- `);
1606
- process.stderr.write(keyValue("From", formatAddress(config.address, true)) + `
1607
- `);
1608
- process.stderr.write(keyValue("To", formatAddress(recipientAddress, true)) + `
1609
- `);
1610
- process.stderr.write(keyValue("Amount", bold(amountNight + " NIGHT")) + `
1611
- `);
1612
- process.stderr.write(`
1613
- `);
1614
- const spinner = start("Starting wallet...");
1615
- try {
1616
- const result = await executeTransfer({
1617
- seedBuffer,
1618
- networkConfig,
1619
- recipientAddress,
1620
- amountNight,
1621
- signal,
1622
- onSync(applied, highest) {
1623
- if (highest > 0) {
1624
- const pct = Math.round(applied / highest * 100);
1625
- spinner.update(`Syncing wallet... ${pct}%`);
1626
- }
1627
- },
1628
- onDust(status) {
1629
- spinner.update(`Dust: ${status}`);
1630
- },
1631
- onProving() {
1632
- spinner.update("Generating ZK proof (this may take a few minutes)...");
1633
- },
1634
- onSubmitting() {
1635
- spinner.update("Submitting transaction...");
1636
- },
1637
- onSyncWarning(_tag, msg) {
1638
- spinner.update(`Syncing wallet... (${msg}, retrying)`);
1639
- }
1640
- });
1641
- spinner.stop("Transaction submitted");
1642
- if (hasFlag(args, "json")) {
1643
- writeJsonResult({
1644
- txHash: result.txHash,
1645
- amount: amountNight,
1646
- recipient: recipientAddress,
1647
- network: networkName
1648
- });
1649
- return;
1650
- }
1651
- process.stdout.write(result.txHash + `
1652
- `);
1653
- process.stderr.write(`
1654
- ` + successMessage(`Transferred ${amountNight} NIGHT`, result.txHash) + `
1655
- `);
1656
- process.stderr.write(`
1657
- ` + divider() + `
1658
- `);
1659
- process.stderr.write(dim(" Verify: midnight balance") + `
1660
-
1661
- `);
1662
- } catch (err) {
1663
- spinner.stop("Failed");
1664
- throw err;
1665
- }
1666
- }
1667
- var init_transfer2 = __esm(() => {
1668
- init_wallet_config();
1669
- init_resolve_network();
1670
- init_transfer();
1671
- init_format();
1672
- init_spinner();
1673
- });
1674
-
1675
- // src/commands/dust.ts
1676
- var exports_dust = {};
1677
- __export(exports_dust, {
1678
- default: () => dustCommand
1679
- });
1680
- import * as ledger4 from "@midnight-ntwrk/ledger-v7";
1681
- import * as rx3 from "rxjs";
1682
- async function dustCommand(args, signal) {
1683
- const subcommand = args.subcommand;
1684
- if (!subcommand || subcommand !== "register" && subcommand !== "status") {
1685
- throw new Error(`Missing or invalid subcommand.
1686
- ` + `Usage:
1687
- ` + ` midnight dust register Register NIGHT UTXOs for dust generation
1688
- ` + " midnight dust status Check dust registration status");
1689
- }
1690
- const walletPath = getFlag(args, "wallet");
1691
- const config = loadWalletConfig(walletPath);
1692
- const seedBuffer = Buffer.from(config.seed, "hex");
1693
- const { name: networkName, config: networkConfig } = resolveNetwork({
1694
- args,
1695
- walletNetwork: config.network,
1696
- address: config.address
1697
- });
1698
- const bundle = buildFacade(seedBuffer, networkConfig);
1699
- const cleanup = async () => {
1700
- try {
1701
- await stopFacade(bundle);
1702
- } catch {
1703
- }
1704
- };
1705
- const onAbort = () => {
1706
- cleanup();
1707
- };
1708
- signal?.addEventListener("abort", onAbort, { once: true });
1709
- const warningRef = {};
1710
- const unsuppress = suppressSdkTransientErrors((tag, msg) => {
1711
- warningRef.current?.(tag, msg);
1712
- });
1713
- const isJson = hasFlag(args, "json");
1714
- try {
1715
- if (subcommand === "register") {
1716
- await dustRegister(bundle, networkName, isJson, signal, warningRef);
1717
- } else {
1718
- await dustStatus(bundle, networkName, isJson, signal, warningRef);
1719
- }
1720
- } finally {
1721
- signal?.removeEventListener("abort", onAbort);
1722
- unsuppress();
1723
- await cleanup();
1724
- }
1725
- }
1726
- async function dustRegister(bundle, networkName, jsonMode, signal, warningRef) {
1727
- process.stderr.write(`
1728
- ` + header("Dust Register") + `
1729
-
1730
- `);
1731
- process.stderr.write(keyValue("Network", networkName) + `
1732
-
1733
- `);
1734
- const spinner = start("Syncing wallet...");
1735
- if (warningRef) {
1736
- warningRef.current = (_tag, msg) => spinner.update(`Syncing wallet... (${msg}, retrying)`);
1737
- }
1738
- try {
1739
- await startAndSyncFacade(bundle, (applied, highest) => {
1740
- if (highest > 0) {
1741
- const pct = Math.round(applied / highest * 100);
1742
- spinner.update(`Syncing wallet... ${pct}%`);
1743
- }
1744
- });
1745
- if (signal?.aborted)
1746
- throw new Error("Operation cancelled");
1747
- spinner.update("Checking dust status...");
1748
- const state = await rx3.firstValueFrom(bundle.facade.state().pipe(rx3.filter((s) => s.isSynced)));
1749
- if (state.dust.availableCoins.length > 0) {
1750
- const dustBal2 = state.dust.walletBalance(new Date);
1751
- spinner.stop("Dust already available");
1752
- if (jsonMode) {
1753
- writeJsonResult({ subcommand: "register", dustBalance: toDust(dustBal2) });
1754
- return;
1755
- }
1756
- process.stdout.write(dustBal2.toString() + `
1757
- `);
1758
- process.stderr.write(`
1759
- ` + successMessage(`Dust tokens already available: ${formatDust(dustBal2)}`) + `
1760
-
1761
- `);
1762
- return;
1763
- }
1764
- const nightUtxos = state.unshielded.availableCoins.filter((coin) => coin.meta?.registeredForDustGeneration !== true);
1765
- let txHash;
1766
- if (nightUtxos.length === 0) {
1767
- spinner.update("All UTXOs already registered, waiting for dust generation...");
1768
- } else {
1769
- spinner.update(`Registering ${nightUtxos.length} UTXO(s) for dust generation...`);
1770
- const dustUtxos = nightUtxos.map((coin) => ({
1771
- ...coin.utxo,
1772
- ctime: new Date(coin.meta.ctime)
1773
- }));
1774
- txHash = await registerNightUtxos(bundle, dustUtxos, state.dust.dustAddress, (status) => {
1775
- spinner.update(status);
1776
- });
1777
- spinner.update(`Registration submitted (${txHash.slice(0, 12)}...), waiting for dust...`);
1778
- }
1779
- if (signal?.aborted)
1780
- throw new Error("Operation cancelled");
1781
- 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)));
1782
- const dustBal = dustState.dust.walletBalance(new Date);
1783
- spinner.stop("Dust registration complete");
1784
- if (jsonMode) {
1785
- const result = { subcommand: "register", dustBalance: toDust(dustBal) };
1786
- if (txHash)
1787
- result.txHash = txHash;
1788
- writeJsonResult(result);
1789
- return;
1790
- }
1791
- process.stdout.write(dustBal.toString() + `
1792
- `);
1793
- process.stderr.write(`
1794
- ` + successMessage(`Dust tokens available: ${formatDust(dustBal)}`) + `
1795
-
1796
- `);
1797
- } catch (err) {
1798
- spinner.stop("Failed");
1799
- throw err;
1800
- }
1801
- }
1802
- async function dustStatus(bundle, networkName, jsonMode, signal, warningRef) {
1803
- process.stderr.write(`
1804
- ` + header("Dust Status") + `
1805
-
1806
- `);
1807
- process.stderr.write(keyValue("Network", networkName) + `
1808
-
1809
- `);
1810
- const spinner = start("Syncing wallet...");
1811
- if (warningRef) {
1812
- warningRef.current = (_tag, msg) => spinner.update(`Syncing wallet... (${msg}, retrying)`);
1813
- }
1814
- try {
1815
- await startAndSyncFacade(bundle, (applied, highest) => {
1816
- if (highest > 0) {
1817
- const pct = Math.round(applied / highest * 100);
1818
- spinner.update(`Syncing wallet... ${pct}%`);
1819
- }
1820
- });
1821
- if (signal?.aborted)
1822
- throw new Error("Operation cancelled");
1823
- spinner.update("Checking dust status...");
1824
- const state = await rx3.firstValueFrom(bundle.facade.state().pipe(rx3.filter((s) => s.isSynced)));
1825
- const dustBalance = state.dust.walletBalance(new Date);
1826
- const hasAvailableDust = state.dust.availableCoins.length > 0;
1827
- const allUtxos = state.unshielded.availableCoins;
1828
- const unregisteredUtxos = allUtxos.filter((coin) => coin.meta?.registeredForDustGeneration !== true);
1829
- const registeredCount = allUtxos.length - unregisteredUtxos.length;
1830
- const unshieldedBalance = state.unshielded.balances[ledger4.unshieldedToken().raw] ?? 0n;
1831
- spinner.stop("Done");
1832
- if (jsonMode) {
1833
- writeJsonResult({
1834
- subcommand: "status",
1835
- dustBalance: toDust(dustBalance),
1836
- registered: registeredCount,
1837
- unregistered: unregisteredUtxos.length,
1838
- nightBalance: toNight(unshieldedBalance),
1839
- dustAvailable: hasAvailableDust
1840
- });
1841
- return;
1842
- }
1843
- process.stdout.write(`dust=${dustBalance}
1844
- `);
1845
- process.stdout.write(`registered=${registeredCount}
1846
- `);
1847
- process.stdout.write(`unregistered=${unregisteredUtxos.length}
1848
- `);
1849
- process.stderr.write(keyValue("NIGHT Balance", bold(formatNight(unshieldedBalance))) + `
1850
- `);
1851
- process.stderr.write(keyValue("Dust Balance", bold(formatDust(dustBalance))) + `
1852
- `);
1853
- process.stderr.write(keyValue("Dust Available", hasAvailableDust ? "yes" : "no") + `
1854
- `);
1855
- process.stderr.write(keyValue("Registered", registeredCount.toString() + " UTXO(s)") + `
1856
- `);
1857
- process.stderr.write(keyValue("Unregistered", unregisteredUtxos.length.toString() + " UTXO(s)") + `
1858
- `);
1859
- process.stderr.write(`
1860
- ` + divider() + `
1861
-
1862
- `);
1863
- } catch (err) {
1864
- spinner.stop("Failed");
1865
- throw err;
1866
- }
1867
- }
1868
- var init_dust = __esm(() => {
1869
- init_wallet_config();
1870
- init_resolve_network();
1871
- init_facade();
1872
- init_transfer();
1873
- init_format();
1874
- init_spinner();
1875
- });
1876
-
1877
- // src/commands/config.ts
1878
- var exports_config = {};
1879
- __export(exports_config, {
1880
- default: () => configCommand
1881
- });
1882
- async function configCommand(args) {
1883
- const action = args.subcommand;
1884
- if (!action || action !== "get" && action !== "set") {
1885
- throw new Error(`Usage: midnight config <get|set> <key> [value]
1886
- ` + `Valid keys: ${getValidConfigKeys().join(", ")}`);
1887
- }
1888
- const key = args.positionals[0];
1889
- if (!key) {
1890
- throw new Error(`Missing config key.
1891
- ` + `Valid keys: ${getValidConfigKeys().join(", ")}`);
1892
- }
1893
- if (action === "get") {
1894
- const value = getConfigValue(key);
1895
- if (hasFlag(args, "json")) {
1896
- writeJsonResult({ action: "get", key, value });
1897
- return;
1898
- }
1899
- process.stdout.write(value + `
1900
- `);
1901
- } else {
1902
- const value = args.positionals[1];
1903
- if (value === undefined) {
1904
- throw new Error(`Missing value for config set.
1905
- Usage: midnight config set ${key} <value>`);
1906
- }
1907
- setConfigValue(key, value);
1908
- if (hasFlag(args, "json")) {
1909
- writeJsonResult({ action: "set", key, value });
1910
- return;
1911
- }
1912
- process.stderr.write(green("✓") + ` ${key} = ${value}
1913
- `);
1914
- }
1915
- }
1916
- var init_config = __esm(() => {
1917
- init_cli_config();
1918
- });
1919
-
1920
- // src/lib/localnet.ts
1921
- import { execSync as execSync2 } from "child_process";
1922
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
1923
- import { homedir as homedir5 } from "os";
1924
- import { join as join5 } from "path";
1925
- function checkDockerAvailable() {
1926
- try {
1927
- const output = execSync2("docker compose version", { ...EXEC_OPTIONS, timeout: 1e4 });
1928
- return output.trim();
1929
- } catch {
1930
- try {
1931
- execSync2("docker --version", { ...EXEC_OPTIONS, timeout: 5000 });
1932
- throw new Error(`Docker Compose v2 is required.
1933
- ` + "Install it from https://docs.docker.com/compose/install/");
1934
- } catch (innerErr) {
1935
- if (innerErr instanceof Error && innerErr.message.includes("Docker Compose v2")) {
1936
- throw innerErr;
1937
- }
1938
- throw new Error(`Docker is required but was not found.
1939
- ` + "Install Docker from https://docs.docker.com/get-docker/");
1940
- }
1941
- }
1942
- }
1943
- function ensureComposeFile() {
1944
- const versionMatches = existsSync4(VERSION_PATH) && existsSync4(COMPOSE_PATH) && readFileSync3(VERSION_PATH, "utf-8").trim() === COMPOSE_VERSION;
1945
- if (versionMatches)
1946
- return false;
1947
- mkdirSync3(LOCALNET_DIR, { recursive: true, mode: DIR_MODE });
1948
- writeFileSync3(COMPOSE_PATH, COMPOSE_YAML, "utf-8");
1949
- writeFileSync3(VERSION_PATH, COMPOSE_VERSION, "utf-8");
1950
- return true;
1951
- }
1952
- function dockerCompose(args) {
1953
- return execSync2(`docker compose -f "${COMPOSE_PATH}" ${args}`, EXEC_OPTIONS);
1954
- }
1955
- function getServiceStatus() {
1956
- try {
1957
- const output = dockerCompose("ps --format json");
1958
- if (!output.trim())
1959
- return [];
1960
- const lines = output.trim().split(`
1961
- `);
1962
- const services = [];
1963
- for (const line of lines) {
1964
- if (!line.trim())
1965
- continue;
1966
- try {
1967
- const obj = JSON.parse(line);
1968
- const name = obj.Service ?? "unknown";
1969
- services.push({
1970
- name,
1971
- state: obj.State ?? "unknown",
1972
- health: obj.Health ?? "",
1973
- port: PORT_MAP[name] ?? ""
1974
- });
1975
- } catch {
1976
- }
1977
- }
1978
- return services;
1979
- } catch {
1980
- return [];
1981
- }
1982
- }
1983
- function waitForHealthy(timeoutMs = 120000, intervalMs = 3000) {
1984
- const deadline = Date.now() + timeoutMs;
1985
- while (Date.now() < deadline) {
1986
- const services = getServiceStatus();
1987
- const allRunning = services.length === 3 && services.every((s) => s.state === "running");
1988
- if (allRunning) {
1989
- const healthyOrNoCheck = services.every((s) => s.health === "healthy" || s.health === "");
1990
- if (healthyOrNoCheck)
1991
- return true;
1992
- }
1993
- execSync2(`sleep ${intervalMs / 1000}`, { timeout: intervalMs + 1000 });
1994
- }
1995
- return false;
1996
- }
1997
- function getComposePath() {
1998
- return COMPOSE_PATH;
1999
- }
2000
- function removeConflictingContainers() {
2001
- const removed = [];
2002
- for (const name of CONTAINER_NAMES) {
2003
- try {
2004
- execSync2(`docker rm -f "${name}"`, { ...EXEC_OPTIONS, timeout: 1e4 });
2005
- removed.push(name);
2006
- } catch {
2007
- }
2008
- }
2009
- return removed;
2010
- }
2011
- var COMPOSE_VERSION = "1.4.0", LOCALNET_DIR, COMPOSE_PATH, VERSION_PATH, COMPOSE_YAML = `services:
58
+ `;var n1=()=>{};function D($){if(!z0())return process.stderr.write(`⠋ ${$}`),{update(q){process.stderr.write(`\r⠋ ${q}`)},stop(q){let Y=q??$;process.stderr.write(`\r✓ ${Y}
59
+ `)}};let Z=0,Q=$,X=()=>{let q=K0(a1[Z]);process.stderr.write(`\r${q} ${Q}\x1B[K`),Z=(Z+1)%a1.length};X();let z=setInterval(X,K2);return{update(q){Q=q},stop(q){clearInterval(z);let Y=q??Q;process.stderr.write(`\r\x1B[32m✓\x1B[0m ${Y}\x1B[K
60
+ `)}}}var a1,K2=80;var q0=M(()=>{a1=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]});var r1={};C(r1,{default:()=>t1});async function t1($){let Z,Q;if($.subcommand)Z=$.subcommand;else{let J=_($,"wallet"),B=c(J);Z=B.address,Q=B.network}if(!Z)throw new Error("No address provided and no wallet file found.");let{name:X,config:z}=i({args:$,walletNetwork:Q,address:Z}),Y=_($,"indexer-ws")??z.indexerWS,K=D(`Checking balance on ${X}...`);try{let J=await o1(Z,Y,(B,U)=>{if(U>0){let G=Math.round(B/U*100);K.update(`Syncing transactions... ${G}%`)}});if(K.stop(`Synced ${J.txCount} transactions`),L($,"json")){let B={};for(let[U,G]of J.balances){let H=H0(U)?"NIGHT":U;B[H]=H0(U)?j0(G):G.toString()}F({address:Z,network:X,balances:B,utxoCount:J.utxoCount,txCount:J.txCount});return}if(J.balances.size===0)process.stdout.write(`0
61
+ `);else for(let[B,U]of J.balances)if(H0(B))process.stdout.write(`NIGHT=${U}
62
+ `);else process.stdout.write(`${B}=${U}
63
+ `);if(process.stderr.write(`
64
+ `+A("Balance")+`
65
+
66
+ `),process.stderr.write(j("Address",R(Z))+`
67
+ `),process.stderr.write(j("Network",X)+`
68
+ `),process.stderr.write(j("UTXOs",J.utxoCount.toString())+`
69
+ `),process.stderr.write(j("Transactions",J.txCount.toString())+`
70
+ `),process.stderr.write(`
71
+ `),J.balances.size===0)process.stderr.write(` ${V("No balance found")}
72
+ `);else for(let[B,U]of J.balances)if(H0(B))process.stderr.write(j("NIGHT",O(D0(U)))+`
73
+ `);else{let G=B.slice(0,8)+"…"+B.slice(-8);process.stderr.write(j(`Token ${G}`,O(U.toString()))+`
74
+ `)}process.stderr.write(`
75
+ `+y()+`
76
+
77
+ `)}catch(J){throw K.stop("Failed"),J}}var s1=M(()=>{e();o();n1();N();q0()});var $3={};C($3,{default:()=>e1});async function e1($){let Z=B1($,"seed","hex").replace(/^0x/,"");if(Z.length!==64||!/^[0-9a-fA-F]+$/.test(Z))throw new Error("Seed must be a 64-character hex string (32 bytes)");let Q=_($,"index"),X=Q!==void 0?parseInt(Q,10):0;if(isNaN(X)||X<0||!Number.isInteger(Number(Q??"0")))throw new Error("Key index must be a non-negative integer");let z=Buffer.from(Z,"hex"),q=s({args:$}),Y=Q0(z,q,X),K=`m/44'/2400'/0'/NightExternal/${X}`;if(L($,"json")){F({address:Y,network:q,index:X,path:K});return}process.stdout.write(Y+`
78
+ `),process.stderr.write(`
79
+ `),process.stderr.write(j("Network",q)+`
80
+ `),process.stderr.write(j("Index",X.toString())+`
81
+ `),process.stderr.write(j("Address",R(Y))+`
82
+ `),process.stderr.write(j("Path",V(K))+`
83
+ `),process.stderr.write(y()+`
84
+
85
+ `)}var Z3=M(()=>{P0();o();N()});var X3={};C(X3,{default:()=>Q3});async function Q3($){let Z=s({args:$}),Q=Buffer.from(O0,"hex"),X=Q0(Q,Z);if(L($,"json")){F({address:X,network:Z});return}process.stdout.write(X+`
86
+ `),process.stderr.write(`
87
+ `),process.stderr.write(j("Network",Z)+`
88
+ `),process.stderr.write(j("Address",R(X))+`
89
+ `),process.stderr.write(j("Seed",V("0x01 (genesis)"))+`
90
+ `),process.stderr.write(y()+`
91
+
92
+ `)}var z3=M(()=>{P0();o();N()});var G3={};C(G3,{default:()=>Y3});import*as q3 from"@midnight-ntwrk/ledger-v7";function W0($,Z,Q){let X={readTime:0n,computeTime:0n,blockUsage:0n,bytesWritten:0n,bytesChurned:0n};X[Z]=Q;let q=$.normalizeFullness(X)[Z];return Math.round(Number(Q)/q)}function U2($){return{readTime:W0($,"readTime",1000000000n),computeTime:W0($,"computeTime",1000000000n),blockUsage:W0($,"blockUsage",10000n),bytesWritten:W0($,"bytesWritten",10000n),bytesChurned:W0($,"bytesChurned",1000000n)}}async function Y3($){let Z=q3.LedgerParameters.initialParameters(),Q=U2(Z);if(L($,"json")){F(Q);return}for(let[X,z]of Object.entries(Q))process.stdout.write(`${X}=${z}
93
+ `);process.stderr.write(`
94
+ `+A("Block Limits")+`
95
+
96
+ `),process.stderr.write(V(" Derived from LedgerParameters.initialParameters()")+`
97
+
98
+ `);for(let[X,z]of Object.entries(Q)){let q=j2[X]??"";process.stderr.write(j(X,`${O(z.toLocaleString())} ${V(q)}`)+`
99
+ `)}process.stderr.write(`
100
+ `+y()+`
101
+ `),process.stderr.write(V(" bytesWritten is typically the tightest constraint")+`
102
+ `),process.stderr.write(V(" for large contract deployments.")+`
103
+
104
+ `)}var j2;var J3=M(()=>{N();j2={readTime:"picoseconds",computeTime:"picoseconds",blockUsage:"bytes",bytesWritten:"bytes",bytesChurned:"bytes"}});import{HDWallet as B2,Roles as r0}from"@midnight-ntwrk/wallet-sdk-hd";function s0($,Z){let Q=B2.fromSeed($);if(Q.type!=="seedOk")throw new Error("Invalid seed for HD wallet");let X=Q.hdWallet.selectAccount(0).selectRole(Z).deriveKeyAt(0);if(X.type==="keyOutOfBounds")throw new Error("Key derivation out of bounds");return X.key}function K3($){return s0($,r0.Zswap)}function U3($){return s0($,r0.NightExternal)}function j3($){return s0($,r0.Dust)}var B3=()=>{};import{ShieldedWallet as H2}from"@midnight-ntwrk/wallet-sdk-shielded";import{UnshieldedWallet as W2,createKeystore as V2,PublicKey as F2,InMemoryTransactionHistoryStorage as L2}from"@midnight-ntwrk/wallet-sdk-unshielded-wallet";import{DustWallet as P2}from"@midnight-ntwrk/wallet-sdk-dust-wallet";import{WalletFacade as M2}from"@midnight-ntwrk/wallet-sdk-facade";import*as Y0 from"@midnight-ntwrk/ledger-v7";import{NetworkId as e0}from"@midnight-ntwrk/wallet-sdk-abstractions";import*as w from"rxjs";function C0($,Z){let Q=O2[Z.networkId];if(Q===void 0)throw new Error(`Unknown networkId: ${Z.networkId}`);let X=K3($),z=U3($),q=j3($),Y=Y0.ZswapSecretKeys.fromSeed(X),K=Y0.DustSecretKey.fromSeed(q),J=V2(z,Q),B={networkId:Q,indexerClientConnection:{indexerHttpUrl:Z.indexer,indexerWsUrl:Z.indexerWS},provingServerUrl:new URL(Z.proofServer),relayURL:new URL(Z.node)},U={networkId:Q,indexerClientConnection:{indexerHttpUrl:Z.indexer,indexerWsUrl:Z.indexerWS},txHistoryStorage:new L2},G={networkId:Q,costParameters:{additionalFeeOverhead:M1,feeBlocksMargin:O1},indexerClientConnection:{indexerHttpUrl:Z.indexer,indexerWsUrl:Z.indexerWS},provingServerUrl:new URL(Z.proofServer),relayURL:new URL(Z.node)},H=H2(B).startWithSecretKeys(Y),W=W2(U).startWithPublicKey(F2.fromKeyStore(J)),P=P2(G).startWithSecretKey(K,Y0.LedgerParameters.initialParameters().dust);return{facade:new M2(H,W,P),keystore:J,zswapSecretKeys:Y,dustSecretKey:K}}async function V0($,Z){let{facade:Q,zswapSecretKeys:X,dustSecretKey:z}=$;return await Q.start(X,z),w.firstValueFrom(Q.state().pipe(w.tap((q)=>{if(Z){let Y=q.unshielded.progress;if(Y)Z(Number(Y.appliedId),Number(Y.highestTransactionId))}}),w.filter((q)=>q.isSynced),w.timeout(_1)))}async function H3($){return w.firstValueFrom($.facade.state().pipe(w.filter((Z)=>Z.isSynced),w.timeout(y1)))}async function v0($){await $.facade.stop()}function w0($){let Z=(X)=>{let z=X?._tag;if(typeof z==="string"&&z.startsWith("Wallet.")){let q=X?.message??"transient error";$?.(z,q);return}Q("Unhandled rejection:",X),process.exit(1)},Q=console.error;return console.error=(...X)=>{let z=X[0];if(typeof z==="object"&&z?._tag?.startsWith("Wallet.")){$?.(z._tag,z?.message??"transient error");return}if(typeof z==="string"&&z.startsWith("Wallet.")){$?.("Wallet.Sync","transient error");return}Q(...X)},process.on("unhandledRejection",Z),()=>{process.removeListener("unhandledRejection",Z),console.error=Q}}var O2;var $1=M(()=>{B3();O2={PreProd:e0.NetworkId.PreProd,Preview:e0.NetworkId.Preview,Undeployed:e0.NetworkId.Undeployed}});import*as Q1 from"@midnight-ntwrk/ledger-v7";import{MidnightBech32m as _2,UnshieldedAddress as y2}from"@midnight-ntwrk/wallet-sdk-address-format";import{NetworkId as Z1}from"@midnight-ntwrk/wallet-sdk-abstractions";import*as b from"rxjs";function I2($){if($<=0)throw new Error("Amount must be greater than 0");if(!Number.isFinite($))throw new Error("Amount must be a finite number");let Z=$.toFixed(6),[Q,X]=Z.split("."),z=Q+(X??"").padEnd(6,"0"),q=BigInt(z);if(q<=0n)throw new Error("Amount too small — minimum is 0.000001 NIGHT");return q}function b0($){let Z=Number($);if(Number.isNaN(Z)||!Number.isFinite(Z))throw new Error(`Invalid amount: "${$}" — must be a positive number`);if(Z<=0)throw new Error(`Invalid amount: "${$}" — must be greater than 0`);return Z}function T2($,Z){let Q=A2[Z.networkId];if(Q===void 0)throw new Error(`Unknown networkId: ${Z.networkId}`);try{_2.parse($).decode(y2,Q)}catch(X){throw new Error(`Invalid recipient address: ${X.message}
105
+ Expected a bech32m address for network "${Z.networkId}"`)}}function R2($){let Z=$;while(Z){let Q=String(Z?.message??"").toLowerCase();if(Q.includes("submission error"))return!0;if(Q.includes("transaction")&&Q.includes("invalid"))return!0;if(Q.includes("138"))return!0;let X=Z?._tag;if(X==="TransactionInvalidError"||X==="SubmissionError")return!0;Z=Z.cause}return!1}function D2($){let Z=Math.round($/1000);if(Z<60)return`${Z}s`;let Q=Math.floor(Z/60),X=Z%60;return`${Q}m ${X}s`}async function E2($,Z,Q){let X=new Date(Date.now()+i0*60*1000);await $.facade.dust.waitForSyncedState();let z=await $.facade.dust.createDustGenerationTransaction(new Date,X,Z,$.keystore.getPublicKey(),Q),q=z.intents?.get(1);if(!q)throw new Error("Dust generation intent not found on transaction");let Y=$.keystore.signData(q.signatureData(1)),K=await $.facade.dust.addDustGenerationSignature(z,Y),J=await $.facade.finalizeTransaction(K);return await $.facade.submitTransaction(J)}async function X1($,Z,Q,X){let z=Date.now(),q=z+I1,Y,K=console.warn,J=console.error,B=(H)=>H.some((W)=>String(W).includes("RPC-CORE")),U=()=>{console.warn=(...H)=>{if(B(H))return;K(...H)},console.error=(...H)=>{if(B(H))return;J(...H)}},G=()=>{console.warn=K,console.error=J};U();try{while(Date.now()<q)try{return await E2($,Z,Q)}catch(H){if(Y=H,R2(H)&&Date.now()+A0<q){let W=D2(Date.now()-z);X?.(`Waiting for dust generation capacity (${W} elapsed, ~5 min on fresh wallets)...`),await new Promise((P)=>setTimeout(P,A0));continue}throw H}throw Y??new Error("Dust registration timed out")}finally{G()}}async function x2($,Z){let Q=await b.firstValueFrom($.facade.state().pipe(b.filter((z)=>z.isSynced))),X=Q.unshielded.availableCoins.filter((z)=>z.meta?.registeredForDustGeneration!==!0);if(X.length>0){Z?.(`Registering ${X.length} UTXO(s) for dust generation...`);let z=X.map((q)=>({...q.utxo,ctime:new Date(q.meta.ctime)}));await X1($,z,Q.dust.dustAddress,Z)}else if(Q.dust.availableCoins.length>0){Z?.("Dust available");return}else Z?.("UTXOs already registered, waiting for dust generation...");Z?.("Waiting for dust tokens..."),await b.firstValueFrom($.facade.state().pipe(b.throttleTime(5000),b.filter((z)=>z.isSynced),b.filter((z)=>z.dust.walletBalance(new Date)>0n),b.timeout(_0))),Z?.("Dust available")}async function N2($,Z,Q,X,z,q){let Y;for(let K=1;K<=y0;K++)try{if(K>1)await H3($);let J=new Date(Date.now()+i0*60*1000),B=await $.facade.transferTransaction([{type:"unshielded",outputs:[{amount:Q,receiverAddress:Z,type:Q1.unshieldedToken().raw}]}],{shieldedSecretKeys:$.zswapSecretKeys,dustSecretKey:$.dustSecretKey},{ttl:J,payFees:!0}),U=await $.facade.signRecipe(B,(W)=>$.keystore.signData(W));X?.();let G=await Promise.race([$.facade.finalizeRecipe(U),new Promise((W,P)=>{setTimeout(()=>P(new Error("ZK proof generation timed out")),A1)})]);return z?.(),await $.facade.submitTransaction(G)}catch(J){if(Y=J,(J?.code===T1||J?.message?.includes("115")||J?.message?.toLowerCase().includes("stale"))&&K<y0)continue;if((J?.message?.toLowerCase().includes("not enough dust")||J?.message?.toLowerCase().includes("dust generated"))&&K<y0){q?.("Waiting for more dust to accumulate..."),await new Promise((G)=>setTimeout(G,A0));continue}throw J}throw Y??new Error("Transfer failed after retries")}async function S0($){let{seedBuffer:Z,networkConfig:Q,recipientAddress:X,amountNight:z,signal:q,onSync:Y,onDust:K,onProving:J,onSubmitting:B,onSyncWarning:U}=$,G=I2(z);T2(X,Q);let H=w0(U),W=C0(Z,Q),P=!1,S=async()=>{if(!P){P=!0;try{await v0(W)}catch{}}},k=()=>{S()};q?.addEventListener("abort",k,{once:!0});try{let h=await V0(W,Y);if(q?.aborted)throw new Error("Operation cancelled");let E=h.unshielded.balances[Q1.unshieldedToken().raw]??0n;if(E<G){let g=Number(E)/P1;throw new Error(`Insufficient balance: ${g.toFixed(6)} NIGHT available, ${z} NIGHT requested`)}if(q?.aborted)throw new Error("Operation cancelled");if(await x2(W,K),q?.aborted)throw new Error("Operation cancelled");return{txHash:await N2(W,X,G,J,B,K),amountMicroNight:G}}finally{q?.removeEventListener("abort",k),H(),await S()}}var A2;var k0=M(()=>{$1();A2={PreProd:Z1.NetworkId.PreProd,Preview:Z1.NetworkId.Preview,Undeployed:Z1.NetworkId.Undeployed}});var V3={};C(V3,{default:()=>W3});async function W3($,Z){let Q=$.subcommand;if(!Q)throw new Error(`Missing amount.
106
+ Usage: midnight airdrop <amount>
107
+ Example: midnight airdrop 1000`);let X=b0(Q),z=_($,"wallet"),q=c(z),{name:Y,config:K}=i({args:$,walletNetwork:q.network,address:q.address});if(Y!=="undeployed")throw new Error(`Airdrop is only available on the "undeployed" network (local devnet).
108
+ Current network: "${Y}"
109
+ On preprod/preview, use a faucet or transfer from another wallet.`);let J=q.address,B=Buffer.from(O0,"hex");process.stderr.write(`
110
+ `+A("Airdrop")+`
111
+
112
+ `),process.stderr.write(j("Network",Y)+`
113
+ `),process.stderr.write(j("From",V("genesis (seed 0x01)"))+`
114
+ `),process.stderr.write(j("To",R(J,!0))+`
115
+ `),process.stderr.write(j("Amount",O(X+" NIGHT"))+`
116
+ `),process.stderr.write(`
117
+ `);let U=D("Starting genesis wallet...");try{let G=await S0({seedBuffer:B,networkConfig:K,recipientAddress:J,amountNight:X,signal:Z,onSync(H,W){if(W>0){let P=Math.round(H/W*100);U.update(`Syncing genesis wallet... ${P}%`)}},onDust(H){U.update(`Dust: ${H}`)},onProving(){U.update("Generating ZK proof (this may take a few minutes)...")},onSubmitting(){U.update("Submitting transaction...")},onSyncWarning(H,W){U.update(`Syncing genesis wallet... (${W}, retrying)`)}});if(U.stop("Transaction submitted"),L($,"json")){F({txHash:G.txHash,amount:X,recipient:J,network:Y});return}process.stdout.write(G.txHash+`
118
+ `),process.stderr.write(`
119
+ `+Z0(`Airdropped ${X} NIGHT to your wallet`,G.txHash)+`
120
+ `),process.stderr.write(`
121
+ `+y()+`
122
+ `),process.stderr.write(V(" Verify: midnight balance")+`
123
+ `),process.stderr.write(V(" Register dust: midnight dust register")+`
124
+ `),process.stderr.write(V(" Note: Dust generation takes a few minutes on a fresh wallet.")+`
125
+ `),process.stderr.write(V(" It will happen automatically on your first transfer.")+`
126
+
127
+ `)}catch(G){if(U.stop("Failed"),G instanceof Error&&G.message.toLowerCase().includes("dust"))throw new Error(`${G.message}
128
+
129
+ On a fresh localnet, the minimum airdrop is ~1 NIGHT.
130
+ Try: midnight airdrop 1`);throw G}}var F3=M(()=>{e();o();k0();N();q0()});var P3={};C(P3,{default:()=>L3});async function L3($,Z){let Q=$.subcommand,X=$.positionals[0];if(!Q)throw new Error(`Missing recipient address.
131
+ Usage: midnight transfer <to> <amount>
132
+ Example: midnight transfer mn_addr_undeployed1... 100`);if(!X)throw new Error(`Missing amount.
133
+ Usage: midnight transfer <to> <amount>
134
+ Example: midnight transfer mn_addr_undeployed1... 100`);let z=b0(X),q=_($,"wallet"),Y=c(q),K=Buffer.from(Y.seed,"hex"),{name:J,config:B}=i({args:$,walletNetwork:Y.network,address:Y.address});process.stderr.write(`
135
+ `+A("Transfer")+`
136
+
137
+ `),process.stderr.write(j("Network",J)+`
138
+ `),process.stderr.write(j("From",R(Y.address,!0))+`
139
+ `),process.stderr.write(j("To",R(Q,!0))+`
140
+ `),process.stderr.write(j("Amount",O(z+" NIGHT"))+`
141
+ `),process.stderr.write(`
142
+ `);let U=D("Starting wallet...");try{let G=await S0({seedBuffer:K,networkConfig:B,recipientAddress:Q,amountNight:z,signal:Z,onSync(H,W){if(W>0){let P=Math.round(H/W*100);U.update(`Syncing wallet... ${P}%`)}},onDust(H){U.update(`Dust: ${H}`)},onProving(){U.update("Generating ZK proof (this may take a few minutes)...")},onSubmitting(){U.update("Submitting transaction...")},onSyncWarning(H,W){U.update(`Syncing wallet... (${W}, retrying)`)}});if(U.stop("Transaction submitted"),L($,"json")){F({txHash:G.txHash,amount:z,recipient:Q,network:J});return}process.stdout.write(G.txHash+`
143
+ `),process.stderr.write(`
144
+ `+Z0(`Transferred ${z} NIGHT`,G.txHash)+`
145
+ `),process.stderr.write(`
146
+ `+y()+`
147
+ `),process.stderr.write(V(" Verify: midnight balance")+`
148
+
149
+ `)}catch(G){throw U.stop("Failed"),G}}var M3=M(()=>{e();o();k0();N();q0()});var y3={};C(y3,{default:()=>_3});import*as O3 from"@midnight-ntwrk/ledger-v7";import*as x from"rxjs";async function _3($,Z){let Q=$.subcommand;if(!Q||Q!=="register"&&Q!=="status")throw new Error(`Missing or invalid subcommand.
150
+ Usage:
151
+ midnight dust register Register NIGHT UTXOs for dust generation
152
+ midnight dust status Check dust registration status`);let X=_($,"wallet"),z=c(X),q=Buffer.from(z.seed,"hex"),{name:Y,config:K}=i({args:$,walletNetwork:z.network,address:z.address}),J=C0(q,K),B=async()=>{try{await v0(J)}catch{}},U=()=>{B()};Z?.addEventListener("abort",U,{once:!0});let G={},H=w0((P,S)=>{G.current?.(P,S)}),W=L($,"json");try{if(Q==="register")await C2(J,Y,W,Z,G);else await v2(J,Y,W,Z,G)}finally{Z?.removeEventListener("abort",U),H(),await B()}}async function C2($,Z,Q,X,z){process.stderr.write(`
153
+ `+A("Dust Register")+`
154
+
155
+ `),process.stderr.write(j("Network",Z)+`
156
+
157
+ `);let q=D("Syncing wallet...");if(z)z.current=(Y,K)=>q.update(`Syncing wallet... (${K}, retrying)`);try{if(await V0($,(G,H)=>{if(H>0){let W=Math.round(G/H*100);q.update(`Syncing wallet... ${W}%`)}}),X?.aborted)throw new Error("Operation cancelled");q.update("Checking dust status...");let Y=await x.firstValueFrom($.facade.state().pipe(x.filter((G)=>G.isSynced)));if(Y.dust.availableCoins.length>0){let G=Y.dust.walletBalance(new Date);if(q.stop("Dust already available"),Q){F({subcommand:"register",dustBalance:B0(G)});return}process.stdout.write(G.toString()+`
158
+ `),process.stderr.write(`
159
+ `+Z0(`Dust tokens already available: ${E0(G)}`)+`
160
+
161
+ `);return}let K=Y.unshielded.availableCoins.filter((G)=>G.meta?.registeredForDustGeneration!==!0),J;if(K.length===0)q.update("All UTXOs already registered, waiting for dust generation...");else{q.update(`Registering ${K.length} UTXO(s) for dust generation...`);let G=K.map((H)=>({...H.utxo,ctime:new Date(H.meta.ctime)}));J=await X1($,G,Y.dust.dustAddress,(H)=>{q.update(H)}),q.update(`Registration submitted (${J.slice(0,12)}...), waiting for dust...`)}if(X?.aborted)throw new Error("Operation cancelled");let U=(await x.firstValueFrom($.facade.state().pipe(x.throttleTime(5000),x.filter((G)=>G.isSynced),x.filter((G)=>G.dust.walletBalance(new Date)>0n),x.timeout(_0)))).dust.walletBalance(new Date);if(q.stop("Dust registration complete"),Q){let G={subcommand:"register",dustBalance:B0(U)};if(J)G.txHash=J;F(G);return}process.stdout.write(U.toString()+`
162
+ `),process.stderr.write(`
163
+ `+Z0(`Dust tokens available: ${E0(U)}`)+`
164
+
165
+ `)}catch(Y){throw q.stop("Failed"),Y}}async function v2($,Z,Q,X,z){process.stderr.write(`
166
+ `+A("Dust Status")+`
167
+
168
+ `),process.stderr.write(j("Network",Z)+`
169
+
170
+ `);let q=D("Syncing wallet...");if(z)z.current=(Y,K)=>q.update(`Syncing wallet... (${K}, retrying)`);try{if(await V0($,(W,P)=>{if(P>0){let S=Math.round(W/P*100);q.update(`Syncing wallet... ${S}%`)}}),X?.aborted)throw new Error("Operation cancelled");q.update("Checking dust status...");let Y=await x.firstValueFrom($.facade.state().pipe(x.filter((W)=>W.isSynced))),K=Y.dust.walletBalance(new Date),J=Y.dust.availableCoins.length>0,B=Y.unshielded.availableCoins,U=B.filter((W)=>W.meta?.registeredForDustGeneration!==!0),G=B.length-U.length,H=Y.unshielded.balances[O3.unshieldedToken().raw]??0n;if(q.stop("Done"),Q){F({subcommand:"status",dustBalance:B0(K),registered:G,unregistered:U.length,nightBalance:j0(H),dustAvailable:J});return}process.stdout.write(`dust=${K}
171
+ `),process.stdout.write(`registered=${G}
172
+ `),process.stdout.write(`unregistered=${U.length}
173
+ `),process.stderr.write(j("NIGHT Balance",O(D0(H)))+`
174
+ `),process.stderr.write(j("Dust Balance",O(E0(K)))+`
175
+ `),process.stderr.write(j("Dust Available",J?"yes":"no")+`
176
+ `),process.stderr.write(j("Registered",G.toString()+" UTXO(s)")+`
177
+ `),process.stderr.write(j("Unregistered",U.length.toString()+" UTXO(s)")+`
178
+ `),process.stderr.write(`
179
+ `+y()+`
180
+
181
+ `)}catch(Y){throw q.stop("Failed"),Y}}var A3=M(()=>{e();o();$1();k0();N();q0()});var T3={};C(T3,{default:()=>I3});async function I3($){let Z=$.subcommand;if(!Z||Z!=="get"&&Z!=="set")throw new Error(`Usage: midnight config <get|set> <key> [value]
182
+ Valid keys: ${a0().join(", ")}`);let Q=$.positionals[0];if(!Q)throw new Error(`Missing config key.
183
+ Valid keys: ${a0().join(", ")}`);if(Z==="get"){let X=N1(Q);if(L($,"json")){F({action:"get",key:Q,value:X});return}process.stdout.write(X+`
184
+ `)}else{let X=$.positionals[1];if(X===void 0)throw new Error(`Missing value for config set.
185
+ Usage: midnight config set ${Q} <value>`);if(C1(Q,X),L($,"json")){F({action:"set",key:Q,value:X});return}process.stderr.write(a("✓")+` ${Q} = ${X}
186
+ `)}}var R3=M(()=>{t0()});import{execSync as F0}from"child_process";import{existsSync as D3,mkdirSync as w2,readFileSync as b2,writeFileSync as E3}from"fs";import{homedir as S2}from"os";import{join as q1}from"path";function N3(){try{return F0("docker compose version",{...f0,timeout:1e4}).trim()}catch{try{throw F0("docker --version",{...f0,timeout:5000}),new Error(`Docker Compose v2 is required.
187
+ Install it from https://docs.docker.com/compose/install/`)}catch($){if($ instanceof Error&&$.message.includes("Docker Compose v2"))throw $;throw new Error(`Docker is required but was not found.
188
+ Install Docker from https://docs.docker.com/get-docker/`)}}}function C3(){if(D3(z1)&&D3(h0)&&b2(z1,"utf-8").trim()===x3)return!1;return w2(Y1,{recursive:!0,mode:r}),E3(h0,k2,"utf-8"),E3(z1,x3,"utf-8"),!0}function G0($){return F0(`docker compose -f "${h0}" ${$}`,f0)}function p0(){try{let $=G0("ps --format json");if(!$.trim())return[];let Z=$.trim().split(`
189
+ `),Q=[];for(let X of Z){if(!X.trim())continue;try{let z=JSON.parse(X),q=z.Service??"unknown";Q.push({name:q,state:z.State??"unknown",health:z.Health??"",port:h2[q]??""})}catch{}}return Q}catch{return[]}}function v3($=120000,Z=3000){let Q=Date.now()+$;while(Date.now()<Q){let X=p0();if(X.length===3&&X.every((q)=>q.state==="running")){if(X.every((Y)=>Y.health==="healthy"||Y.health===""))return!0}F0(`sleep ${Z/1000}`,{timeout:Z+1000})}return!1}function G1(){return h0}function w3(){let $=[];for(let Z of f2)try{F0(`docker rm -f "${Z}"`,{...f0,timeout:1e4}),$.push(Z)}catch{}return $}var x3="1.4.0",Y1,h0,z1,k2=`services:
2012
190
  proof-server:
2013
191
  image: 'nel349/proof-server:7.0.0'
2014
192
  container_name: "proof-server"
@@ -2050,770 +228,45 @@ var COMPOSE_VERSION = "1.4.0", LOCALNET_DIR, COMPOSE_PATH, VERSION_PATH, COMPOSE
2050
228
  start_period: 5s
2051
229
  environment:
2052
230
  CFG_PRESET: "dev"
2053
- `, EXEC_OPTIONS, PORT_MAP, CONTAINER_NAMES;
2054
- var init_localnet = __esm(() => {
2055
- LOCALNET_DIR = join5(homedir5(), MIDNIGHT_DIR, LOCALNET_DIR_NAME);
2056
- COMPOSE_PATH = join5(LOCALNET_DIR, "compose.yml");
2057
- VERSION_PATH = join5(LOCALNET_DIR, ".version");
2058
- EXEC_OPTIONS = {
2059
- encoding: "utf-8",
2060
- timeout: 30000
2061
- };
2062
- PORT_MAP = {
2063
- node: "9944",
2064
- indexer: "8088",
2065
- "proof-server": "6300"
2066
- };
2067
- CONTAINER_NAMES = ["node", "indexer", "proof-server"];
2068
- });
2069
-
2070
- // src/commands/localnet.ts
2071
- var exports_localnet = {};
2072
- __export(exports_localnet, {
2073
- default: () => localnetCommand
2074
- });
2075
- import { spawn } from "child_process";
2076
- function isValidSubcommand(s) {
2077
- return VALID_SUBCOMMANDS.includes(s);
2078
- }
2079
- function formatServiceTable(services) {
2080
- const lines = [];
2081
- for (const svc of services) {
2082
- const stateColor = svc.state === "running" ? green : red;
2083
- const healthStr = svc.health ? ` (${svc.health})` : "";
2084
- const portStr = svc.port ? `:${svc.port}` : "";
2085
- lines.push(` ${svc.name.padEnd(16)}${stateColor(svc.state)}${dim(healthStr)}${dim(portStr)}`);
2086
- }
2087
- return lines.join(`
2088
- `);
2089
- }
2090
- async function handleUp(jsonMode) {
2091
- const wrote = ensureComposeFile();
2092
- if (wrote) {
2093
- process.stderr.write(dim(` Wrote compose.yml to ${getComposePath()}`) + `
2094
- `);
2095
- }
2096
- const spinner = start("Starting local network...");
2097
- try {
2098
- dockerCompose("up -d");
2099
- spinner.update("Waiting for services to be healthy...");
2100
- const healthy = waitForHealthy(120000);
2101
- if (!healthy) {
2102
- spinner.stop(yellow("Services started but not all healthy yet"));
2103
- process.stderr.write(`
2104
- ` + dim(" Tip: run ") + bold("midnight localnet logs") + dim(" to check for errors") + `
2105
- `);
2106
- } else {
2107
- spinner.stop("Local network is running");
2108
- }
2109
- } catch (err) {
2110
- spinner.stop(red("Failed to start local network"));
2111
- if (err instanceof Error) {
2112
- if (err.message.includes("is already in use by container")) {
2113
- throw new Error(`Container name conflict — containers with the same names already exist
2114
- ` + `(likely from a previous midnight-local-network setup).
2115
-
2116
- ` + 'Run "midnight localnet clean" to remove them, then try again.');
2117
- }
2118
- if (err.message.includes("address already in use")) {
2119
- throw new Error(`Port conflict detected — another process is using a required port.
2120
- ` + "Check ports 9944, 8088, and 6300, then try again.");
2121
- }
2122
- }
2123
- throw err;
2124
- }
2125
- const services = getServiceStatus();
2126
- if (jsonMode) {
2127
- writeJsonResult({
2128
- subcommand: "up",
2129
- services: services.map((s) => ({ name: s.name, state: s.state, port: s.port, health: s.health }))
2130
- });
2131
- return;
2132
- }
2133
- if (services.length > 0) {
2134
- process.stderr.write(`
2135
- ` + formatServiceTable(services) + `
2136
- `);
2137
- }
2138
- for (const svc of services) {
2139
- process.stdout.write(`${svc.name}=${svc.state}:${svc.port}
2140
- `);
2141
- }
2142
- process.stderr.write(`
2143
- ` + dim(" Next: ") + bold("midnight generate --network undeployed") + `
2144
- `);
2145
- }
2146
- async function handleStop(jsonMode) {
2147
- const spinner = start("Stopping local network...");
2148
- try {
2149
- dockerCompose("stop");
2150
- spinner.stop("Local network stopped (containers preserved)");
2151
- if (jsonMode) {
2152
- writeJsonResult({ subcommand: "stop", status: "stopped" });
2153
- return;
2154
- }
2155
- } catch (err) {
2156
- spinner.stop(red("Failed to stop local network"));
2157
- throw err;
2158
- }
2159
- }
2160
- async function handleDown(jsonMode) {
2161
- const spinner = start("Tearing down local network...");
2162
- try {
2163
- dockerCompose("down --volumes");
2164
- spinner.stop("Local network removed (containers, networks, volumes)");
2165
- if (jsonMode) {
2166
- writeJsonResult({ subcommand: "down", status: "removed" });
2167
- return;
2168
- }
2169
- } catch (err) {
2170
- spinner.stop(red("Failed to tear down local network"));
2171
- throw err;
2172
- }
2173
- }
2174
- async function handleStatus(jsonMode) {
2175
- const services = getServiceStatus();
2176
- if (jsonMode) {
2177
- writeJsonResult({
2178
- subcommand: "status",
2179
- services: services.map((s) => ({ name: s.name, state: s.state, port: s.port, health: s.health }))
2180
- });
2181
- return;
2182
- }
2183
- if (services.length === 0) {
2184
- process.stderr.write(`
2185
- ` + header("Localnet Status") + `
2186
-
2187
- `);
2188
- process.stderr.write(dim(" No services running.") + `
2189
- `);
2190
- process.stderr.write(dim(" Run ") + bold("midnight localnet up") + dim(" to start.") + `
2191
-
2192
- `);
2193
- return;
2194
- }
2195
- process.stderr.write(`
2196
- ` + header("Localnet Status") + `
2197
-
2198
- `);
2199
- process.stderr.write(formatServiceTable(services) + `
2200
- `);
2201
- process.stderr.write(`
2202
- ` + divider() + `
2203
-
2204
- `);
2205
- for (const svc of services) {
2206
- process.stdout.write(`${svc.name}=${svc.state}:${svc.port}
2207
- `);
2208
- }
2209
- }
2210
- async function handleClean(jsonMode) {
2211
- const spinner = start("Removing conflicting containers...");
2212
- try {
2213
- try {
2214
- dockerCompose("down");
2215
- } catch {
2216
- }
2217
- const removed = removeConflictingContainers();
2218
- if (removed.length > 0) {
2219
- spinner.stop(`Removed ${removed.length} container${removed.length > 1 ? "s" : ""}: ${removed.join(", ")}`);
2220
- } else {
2221
- spinner.stop("No conflicting containers found");
2222
- }
2223
- if (jsonMode) {
2224
- writeJsonResult({ subcommand: "clean", status: "cleaned", removed });
2225
- return;
2226
- }
2227
- } catch (err) {
2228
- spinner.stop(red("Failed to clean up"));
2229
- throw err;
2230
- }
2231
- }
2232
- async function handleLogs() {
2233
- const composePath = getComposePath();
2234
- const child = spawn("docker", ["compose", "-f", composePath, "logs", "-f"], {
2235
- stdio: "inherit"
2236
- });
2237
- return new Promise((resolve4, reject) => {
2238
- child.on("close", (code) => {
2239
- if (code === 0 || code === 130 || code === null) {
2240
- resolve4();
2241
- } else {
2242
- reject(new Error(`docker compose logs exited with code ${code}`));
2243
- }
2244
- });
2245
- child.on("error", reject);
2246
- });
2247
- }
2248
- async function localnetCommand(args) {
2249
- const subcommand = args.subcommand;
2250
- if (!subcommand || !isValidSubcommand(subcommand)) {
2251
- throw new Error(`Usage: midnight localnet <${VALID_SUBCOMMANDS.join("|")}>
2252
-
2253
- ` + `Subcommands:
2254
- ` + ` up Start the local network
2255
- ` + ` stop Stop containers (preserves state)
2256
- ` + ` down Remove containers, networks, volumes
2257
- ` + ` status Show service status
2258
- ` + ` logs Stream service logs
2259
- ` + ` clean Remove conflicting containers
2260
-
2261
- ` + `Example: midnight localnet up`);
2262
- }
2263
- checkDockerAvailable();
2264
- const jsonMode = hasFlag(args, "json");
2265
- process.stderr.write(`
2266
- ` + header("Localnet") + `
2267
-
2268
- `);
2269
- switch (subcommand) {
2270
- case "up":
2271
- return handleUp(jsonMode);
2272
- case "stop":
2273
- return handleStop(jsonMode);
2274
- case "down":
2275
- return handleDown(jsonMode);
2276
- case "status":
2277
- return handleStatus(jsonMode);
2278
- case "logs":
2279
- return handleLogs();
2280
- case "clean":
2281
- return handleClean(jsonMode);
2282
- }
2283
- }
2284
- var VALID_SUBCOMMANDS;
2285
- var init_localnet2 = __esm(() => {
2286
- init_localnet();
2287
- init_format();
2288
- init_spinner();
2289
- VALID_SUBCOMMANDS = ["up", "stop", "down", "status", "logs", "clean"];
2290
- });
2291
-
2292
- // src/mcp-server.ts
2293
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2294
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
2295
- import { ListToolsRequestSchema, CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
2296
-
2297
- // src/lib/run-command.ts
2298
- async function captureCommand(handler, args, signal) {
2299
- const chunks = [];
2300
- setCaptureTarget((json) => chunks.push(json));
2301
- const originalStderr = process.stderr.write;
2302
- process.stderr.write = () => true;
2303
- try {
2304
- args.flags.json = true;
2305
- await handler(args, signal);
2306
- const raw = chunks.join("").trim();
2307
- if (!raw)
2308
- return {};
2309
- return JSON.parse(raw);
2310
- } finally {
2311
- setCaptureTarget(null);
2312
- process.stderr.write = originalStderr;
2313
- }
2314
- }
2315
-
2316
- // src/lib/exit-codes.ts
2317
- var EXIT_GENERAL_ERROR = 1;
2318
- var EXIT_INVALID_ARGS = 2;
2319
- var EXIT_WALLET_NOT_FOUND = 3;
2320
- var EXIT_NETWORK_ERROR = 4;
2321
- var EXIT_INSUFFICIENT_BALANCE = 5;
2322
- var EXIT_TX_REJECTED = 6;
2323
- var EXIT_CANCELLED = 7;
2324
- var ERROR_CODES = {
2325
- INVALID_ARGS: "INVALID_ARGS",
2326
- WALLET_NOT_FOUND: "WALLET_NOT_FOUND",
2327
- NETWORK_ERROR: "NETWORK_ERROR",
2328
- INSUFFICIENT_BALANCE: "INSUFFICIENT_BALANCE",
2329
- TX_REJECTED: "TX_REJECTED",
2330
- STALE_UTXO: "STALE_UTXO",
2331
- PROOF_TIMEOUT: "PROOF_TIMEOUT",
2332
- DUST_REQUIRED: "DUST_REQUIRED",
2333
- CANCELLED: "CANCELLED",
2334
- UNKNOWN: "UNKNOWN"
2335
- };
2336
- function classifyError(err) {
2337
- const msg = (err.message ?? "").toLowerCase();
2338
- if (msg.includes("operation cancelled") || msg.includes("operation aborted") || msg === "cancelled" || msg === "aborted") {
2339
- return { exitCode: EXIT_CANCELLED, errorCode: ERROR_CODES.CANCELLED };
2340
- }
2341
- if (msg.includes("wallet file not found") || msg.includes("wallet") && msg.includes("not found")) {
2342
- return { exitCode: EXIT_WALLET_NOT_FOUND, errorCode: ERROR_CODES.WALLET_NOT_FOUND };
2343
- }
2344
- 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:")) {
2345
- return { exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.INVALID_ARGS };
2346
- }
2347
- if (msg.includes("proof") && msg.includes("timeout")) {
2348
- return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.PROOF_TIMEOUT };
2349
- }
2350
- if (msg.includes("stale utxo") || msg.includes("error code 115") || msg.includes("errorcode: 115")) {
2351
- return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.STALE_UTXO };
2352
- }
2353
- if (msg.includes("no dust") || msg.includes("dust") && (msg.includes("required") || msg.includes("available") || msg.includes("insufficient"))) {
2354
- return { exitCode: EXIT_INSUFFICIENT_BALANCE, errorCode: ERROR_CODES.DUST_REQUIRED };
2355
- }
2356
- if (msg.includes("insufficient") || msg.includes("not enough")) {
2357
- return { exitCode: EXIT_INSUFFICIENT_BALANCE, errorCode: ERROR_CODES.INSUFFICIENT_BALANCE };
2358
- }
2359
- if (msg.includes("rejected") || msg.includes("transaction failed")) {
2360
- return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.TX_REJECTED };
2361
- }
2362
- if (msg.includes("econnrefused") || msg.includes("enotfound") || msg.includes("etimedout") || msg.includes("websocket") || msg.includes("connection refused") || msg.includes("network") && msg.includes("error")) {
2363
- return { exitCode: EXIT_NETWORK_ERROR, errorCode: ERROR_CODES.NETWORK_ERROR };
2364
- }
2365
- return { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.UNKNOWN };
2366
- }
2367
- // package.json
2368
- var package_default = {
2369
- name: "midnight-wallet-cli",
2370
- version: "0.1.7",
2371
- type: "module",
2372
- description: "Git-style CLI wallet for the Midnight blockchain",
2373
- license: "Apache-2.0",
2374
- bin: {
2375
- midnight: "dist/wallet.js",
2376
- mn: "dist/wallet.js",
2377
- "midnight-wallet-cli": "dist/wallet.js",
2378
- "midnight-wallet-mcp": "dist/mcp-server.js"
2379
- },
2380
- files: [
2381
- "dist"
2382
- ],
2383
- scripts: {
2384
- wallet: "tsx src/wallet.ts",
2385
- build: 'bun build src/wallet.ts --outfile dist/wallet.js --target node --format esm --packages external --banner "#!/usr/bin/env node" && bun build src/mcp-server.ts --outfile dist/mcp-server.js --target node --format esm --packages external --banner "#!/usr/bin/env node"',
2386
- mcp: "tsx src/mcp-server.ts",
2387
- prepublishOnly: "npm run build && npm run test",
2388
- test: "vitest run",
2389
- "test:watch": "vitest",
2390
- typecheck: "tsc --noEmit"
2391
- },
2392
- dependencies: {
2393
- "@midnight-ntwrk/ledger-v7": "7.0.0",
2394
- "@midnight-ntwrk/midnight-js-network-id": "3.0.0",
2395
- "@midnight-ntwrk/midnight-js-types": "3.0.0",
2396
- "@midnight-ntwrk/wallet-sdk-abstractions": "1.0.0",
2397
- "@midnight-ntwrk/wallet-sdk-address-format": "3.0.0",
2398
- "@midnight-ntwrk/wallet-sdk-dust-wallet": "1.0.0",
2399
- "@midnight-ntwrk/wallet-sdk-facade": "1.0.0",
2400
- "@midnight-ntwrk/wallet-sdk-hd": "3.0.0",
2401
- "@midnight-ntwrk/wallet-sdk-shielded": "1.0.0",
2402
- "@midnight-ntwrk/wallet-sdk-unshielded-wallet": "1.0.0",
2403
- "@modelcontextprotocol/sdk": "^1.27.1",
2404
- "@scure/bip39": "^2.0.1",
2405
- rxjs: "^7.8.1",
2406
- ws: "^8.19.0"
2407
- },
2408
- devDependencies: {
2409
- "@types/node": "^22.19.13",
2410
- "@types/ws": "^8.18.1",
2411
- tsx: "^4.21.0",
2412
- typescript: "^5.9.3",
2413
- vitest: "^3.2.4"
2414
- }
2415
- };
2416
-
2417
- // src/lib/pkg.ts
2418
- var PKG_NAME = package_default.name;
2419
- var PKG_VERSION = package_default.version;
2420
- var PKG_DESCRIPTION = package_default.description;
2421
-
2422
- // src/mcp-server.ts
2423
- function buildArgs(command, params, subcommand) {
2424
- const flags = { json: true };
2425
- const positionals = [];
2426
- for (const [key, value] of Object.entries(params)) {
2427
- if (value === undefined || value === null)
2428
- continue;
2429
- if (typeof value === "boolean") {
2430
- if (value)
2431
- flags[key] = true;
2432
- } else {
2433
- flags[key] = String(value);
2434
- }
2435
- }
2436
- return {
2437
- command,
2438
- subcommand,
2439
- positionals,
2440
- flags
2441
- };
2442
- }
2443
- var handlerLoaders = {
2444
- generate: () => Promise.resolve().then(() => (init_generate(), exports_generate)),
2445
- info: () => Promise.resolve().then(() => (init_info(), exports_info)),
2446
- balance: () => Promise.resolve().then(() => (init_balance(), exports_balance)),
2447
- address: () => Promise.resolve().then(() => (init_address(), exports_address)),
2448
- "genesis-address": () => Promise.resolve().then(() => (init_genesis_address(), exports_genesis_address)),
2449
- "inspect-cost": () => Promise.resolve().then(() => (init_inspect_cost(), exports_inspect_cost)),
2450
- airdrop: () => Promise.resolve().then(() => (init_airdrop(), exports_airdrop)),
2451
- transfer: () => Promise.resolve().then(() => (init_transfer2(), exports_transfer)),
2452
- dust: () => Promise.resolve().then(() => (init_dust(), exports_dust)),
2453
- config: () => Promise.resolve().then(() => (init_config(), exports_config)),
2454
- localnet: () => Promise.resolve().then(() => (init_localnet2(), exports_localnet))
2455
- };
2456
- async function importHandler(name) {
2457
- const loader = handlerLoaders[name];
2458
- if (!loader)
2459
- throw new Error(`Unknown command handler: ${name}`);
2460
- const mod = await loader();
2461
- return mod.default;
2462
- }
2463
- var TOOLS = [
2464
- {
2465
- name: "midnight_generate",
2466
- description: "Generate a new wallet (random mnemonic, or restore from seed/mnemonic)",
2467
- inputSchema: {
2468
- type: "object",
2469
- properties: {
2470
- network: { type: "string", description: "Network: preprod, preview, undeployed", enum: ["preprod", "preview", "undeployed"] },
2471
- seed: { type: "string", description: "Restore from existing seed (64-char hex)" },
2472
- mnemonic: { type: "string", description: "Restore from BIP-39 mnemonic (24 words)" },
2473
- output: { type: "string", description: "Custom output path (default: ~/.midnight/wallet.json)" },
2474
- force: { type: "string", description: 'Set to "true" to overwrite existing wallet file' }
2475
- }
2476
- },
2477
- async handler(params) {
2478
- const args = buildArgs("generate", params);
2479
- if (params.force === "true" || params.force === true)
2480
- args.flags.force = true;
2481
- const handler = await importHandler("generate");
2482
- return captureCommand(handler, args);
2483
- }
2484
- },
2485
- {
2486
- name: "midnight_info",
2487
- description: "Display wallet address, network, creation date (no secrets shown)",
2488
- inputSchema: {
2489
- type: "object",
2490
- properties: {
2491
- wallet: { type: "string", description: "Custom wallet file path" }
2492
- }
2493
- },
2494
- async handler(params) {
2495
- const args = buildArgs("info", params);
2496
- const handler = await importHandler("info");
2497
- return captureCommand(handler, args);
2498
- }
2499
- },
2500
- {
2501
- name: "midnight_balance",
2502
- description: "Check unshielded balance via indexer subscription",
2503
- inputSchema: {
2504
- type: "object",
2505
- properties: {
2506
- address: { type: "string", description: "Address to check (or reads from wallet file)" },
2507
- wallet: { type: "string", description: "Custom wallet file path" },
2508
- network: { type: "string", description: "Override network detection", enum: ["preprod", "preview", "undeployed"] },
2509
- "indexer-ws": { type: "string", description: "Custom indexer WebSocket URL" }
2510
- }
2511
- },
2512
- async handler(params) {
2513
- const address = params.address;
2514
- const args = buildArgs("balance", params, address);
2515
- delete args.flags.address;
2516
- const handler = await importHandler("balance");
2517
- return captureCommand(handler, args);
2518
- }
2519
- },
2520
- {
2521
- name: "midnight_address",
2522
- description: "Derive and display an unshielded address from a seed",
2523
- inputSchema: {
2524
- type: "object",
2525
- properties: {
2526
- seed: { type: "string", description: "Seed to derive from (required, 64-char hex)" },
2527
- network: { type: "string", description: "Network for address prefix", enum: ["preprod", "preview", "undeployed"] },
2528
- index: { type: "string", description: "Key derivation index (default: 0)" }
2529
- },
2530
- required: ["seed"]
2531
- },
2532
- async handler(params) {
2533
- const args = buildArgs("address", params);
2534
- const handler = await importHandler("address");
2535
- return captureCommand(handler, args);
2536
- }
2537
- },
2538
- {
2539
- name: "midnight_genesis_address",
2540
- description: "Display the genesis wallet address (seed 0x01) for a network",
2541
- inputSchema: {
2542
- type: "object",
2543
- properties: {
2544
- network: { type: "string", description: "Network for address prefix", enum: ["preprod", "preview", "undeployed"] }
2545
- }
2546
- },
2547
- async handler(params) {
2548
- const args = buildArgs("genesis-address", params);
2549
- const handler = await importHandler("genesis-address");
2550
- return captureCommand(handler, args);
2551
- }
2552
- },
2553
- {
2554
- name: "midnight_inspect_cost",
2555
- description: "Display current block limits derived from LedgerParameters",
2556
- inputSchema: {
2557
- type: "object",
2558
- properties: {}
2559
- },
2560
- async handler() {
2561
- const args = buildArgs("inspect-cost", {});
2562
- const handler = await importHandler("inspect-cost");
2563
- return captureCommand(handler, args);
2564
- }
2565
- },
2566
- {
2567
- name: "midnight_airdrop",
2568
- description: "Fund your wallet from the genesis wallet (undeployed network only)",
2569
- inputSchema: {
2570
- type: "object",
2571
- properties: {
2572
- amount: { type: "string", description: "Amount in NIGHT to airdrop" },
2573
- wallet: { type: "string", description: "Custom wallet file path" }
2574
- },
2575
- required: ["amount"]
2576
- },
2577
- async handler(params) {
2578
- const amount = params.amount;
2579
- const args = buildArgs("airdrop", params, amount);
2580
- delete args.flags.amount;
2581
- const handler = await importHandler("airdrop");
2582
- return captureCommand(handler, args);
2583
- }
2584
- },
2585
- {
2586
- name: "midnight_transfer",
2587
- description: "Send NIGHT tokens to another address",
2588
- inputSchema: {
2589
- type: "object",
2590
- properties: {
2591
- to: { type: "string", description: "Recipient bech32m address" },
2592
- amount: { type: "string", description: "Amount in NIGHT to send" },
2593
- wallet: { type: "string", description: "Custom wallet file path" }
2594
- },
2595
- required: ["to", "amount"]
2596
- },
2597
- async handler(params) {
2598
- const to = params.to;
2599
- const amount = params.amount;
2600
- const args = buildArgs("transfer", params, to);
2601
- args.positionals = [amount];
2602
- delete args.flags.to;
2603
- delete args.flags.amount;
2604
- const handler = await importHandler("transfer");
2605
- return captureCommand(handler, args);
2606
- }
2607
- },
2608
- {
2609
- name: "midnight_dust_register",
2610
- description: "Register NIGHT UTXOs for dust (fee token) generation",
2611
- inputSchema: {
2612
- type: "object",
2613
- properties: {
2614
- wallet: { type: "string", description: "Custom wallet file path" }
2615
- }
2616
- },
2617
- async handler(params) {
2618
- const args = buildArgs("dust", params, "register");
2619
- const handler = await importHandler("dust");
2620
- return captureCommand(handler, args);
2621
- }
2622
- },
2623
- {
2624
- name: "midnight_dust_status",
2625
- description: "Check dust registration status and balance",
2626
- inputSchema: {
2627
- type: "object",
2628
- properties: {
2629
- wallet: { type: "string", description: "Custom wallet file path" }
2630
- }
2631
- },
2632
- async handler(params) {
2633
- const args = buildArgs("dust", params, "status");
2634
- const handler = await importHandler("dust");
2635
- return captureCommand(handler, args);
2636
- }
2637
- },
2638
- {
2639
- name: "midnight_config_get",
2640
- description: "Read a persistent config value",
2641
- inputSchema: {
2642
- type: "object",
2643
- properties: {
2644
- key: { type: "string", description: 'Config key to read (e.g. "network")' }
2645
- },
2646
- required: ["key"]
2647
- },
2648
- async handler(params) {
2649
- const key = params.key;
2650
- const args = {
2651
- command: "config",
2652
- subcommand: "get",
2653
- positionals: [key],
2654
- flags: { json: true }
2655
- };
2656
- const handler = await importHandler("config");
2657
- return captureCommand(handler, args);
2658
- }
2659
- },
2660
- {
2661
- name: "midnight_config_set",
2662
- description: "Write a persistent config value",
2663
- inputSchema: {
2664
- type: "object",
2665
- properties: {
2666
- key: { type: "string", description: 'Config key to set (e.g. "network")' },
2667
- value: { type: "string", description: "Config value to set" }
2668
- },
2669
- required: ["key", "value"]
2670
- },
2671
- async handler(params) {
2672
- const key = params.key;
2673
- const value = params.value;
2674
- const args = {
2675
- command: "config",
2676
- subcommand: "set",
2677
- positionals: [key, value],
2678
- flags: { json: true }
2679
- };
2680
- const handler = await importHandler("config");
2681
- return captureCommand(handler, args);
2682
- }
2683
- },
2684
- {
2685
- name: "midnight_localnet_up",
2686
- description: "Start a local Midnight network via Docker Compose",
2687
- inputSchema: {
2688
- type: "object",
2689
- properties: {}
2690
- },
2691
- async handler() {
2692
- const args = {
2693
- command: "localnet",
2694
- subcommand: "up",
2695
- positionals: [],
2696
- flags: { json: true }
2697
- };
2698
- const handler = await importHandler("localnet");
2699
- return captureCommand(handler, args);
2700
- }
2701
- },
2702
- {
2703
- name: "midnight_localnet_stop",
2704
- description: "Stop local network containers (preserves state for fast restart)",
2705
- inputSchema: {
2706
- type: "object",
2707
- properties: {}
2708
- },
2709
- async handler() {
2710
- const args = {
2711
- command: "localnet",
2712
- subcommand: "stop",
2713
- positionals: [],
2714
- flags: { json: true }
2715
- };
2716
- const handler = await importHandler("localnet");
2717
- return captureCommand(handler, args);
2718
- }
2719
- },
2720
- {
2721
- name: "midnight_localnet_down",
2722
- description: "Remove local network containers, networks, and volumes (full teardown)",
2723
- inputSchema: {
2724
- type: "object",
2725
- properties: {}
2726
- },
2727
- async handler() {
2728
- const args = {
2729
- command: "localnet",
2730
- subcommand: "down",
2731
- positionals: [],
2732
- flags: { json: true }
2733
- };
2734
- const handler = await importHandler("localnet");
2735
- return captureCommand(handler, args);
2736
- }
2737
- },
2738
- {
2739
- name: "midnight_localnet_status",
2740
- description: "Show local network service status and ports",
2741
- inputSchema: {
2742
- type: "object",
2743
- properties: {}
2744
- },
2745
- async handler() {
2746
- const args = {
2747
- command: "localnet",
2748
- subcommand: "status",
2749
- positionals: [],
2750
- flags: { json: true }
2751
- };
2752
- const handler = await importHandler("localnet");
2753
- return captureCommand(handler, args);
2754
- }
2755
- },
2756
- {
2757
- name: "midnight_localnet_clean",
2758
- description: "Remove conflicting containers from other setups",
2759
- inputSchema: {
2760
- type: "object",
2761
- properties: {}
2762
- },
2763
- async handler() {
2764
- const args = {
2765
- command: "localnet",
2766
- subcommand: "clean",
2767
- positionals: [],
2768
- flags: { json: true }
2769
- };
2770
- const handler = await importHandler("localnet");
2771
- return captureCommand(handler, args);
2772
- }
2773
- }
2774
- ];
2775
- var server = new Server({ name: "midnight-wallet-cli", version: PKG_VERSION }, { capabilities: { tools: {} } });
2776
- server.setRequestHandler(ListToolsRequestSchema, async () => {
2777
- return {
2778
- tools: TOOLS.map((t) => ({
2779
- name: t.name,
2780
- description: t.description,
2781
- inputSchema: t.inputSchema
2782
- }))
2783
- };
2784
- });
2785
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
2786
- const { name, arguments: params } = request.params;
2787
- const tool = TOOLS.find((t) => t.name === name);
2788
- if (!tool) {
2789
- return {
2790
- content: [{ type: "text", text: `Unknown tool: ${name}` }],
2791
- isError: true
2792
- };
2793
- }
2794
- try {
2795
- const result = await tool.handler(params ?? {});
2796
- return {
2797
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
2798
- };
2799
- } catch (err) {
2800
- const error = err instanceof Error ? err : new Error(String(err));
2801
- const { errorCode } = classifyError(error);
2802
- return {
2803
- content: [{
2804
- type: "text",
2805
- text: JSON.stringify({ error: true, code: errorCode, message: error.message })
2806
- }],
2807
- isError: true
2808
- };
2809
- }
2810
- });
2811
- async function main() {
2812
- const transport = new StdioServerTransport;
2813
- await server.connect(transport);
2814
- }
2815
- main().catch((err) => {
2816
- process.stderr.write(`MCP server error: ${err.message}
2817
- `);
2818
- process.exit(1);
2819
- });
231
+ `,f0,h2,f2;var b3=M(()=>{Y1=q1(S2(),p,D1),h0=q1(Y1,"compose.yml"),z1=q1(Y1,".version"),f0={encoding:"utf-8",timeout:30000};h2={node:"9944",indexer:"8088","proof-server":"6300"};f2=["node","indexer","proof-server"]});var f3={};C(f3,{default:()=>h3});import{spawn as p2}from"child_process";function c2($){return S3.includes($)}function k3($){let Z=[];for(let Q of $){let X=Q.state==="running"?a:$0,z=Q.health?` (${Q.health})`:"",q=Q.port?`:${Q.port}`:"";Z.push(` ${Q.name.padEnd(16)}${X(Q.state)}${V(z)}${V(q)}`)}return Z.join(`
232
+ `)}async function m2($){if(C3())process.stderr.write(V(` Wrote compose.yml to ${G1()}`)+`
233
+ `);let Q=D("Starting local network...");try{if(G0("up -d"),Q.update("Waiting for services to be healthy..."),!v3(120000))Q.stop(U0("Services started but not all healthy yet")),process.stderr.write(`
234
+ `+V(" Tip: run ")+O("midnight localnet logs")+V(" to check for errors")+`
235
+ `);else Q.stop("Local network is running")}catch(z){if(Q.stop($0("Failed to start local network")),z instanceof Error){if(z.message.includes("is already in use by container"))throw new Error(`Container name conflict — containers with the same names already exist
236
+ `+`(likely from a previous midnight-local-network setup).
237
+
238
+ Run "midnight localnet clean" to remove them, then try again.`);if(z.message.includes("address already in use"))throw new Error(`Port conflict detected — another process is using a required port.
239
+ `+"Check ports 9944, 8088, and 6300, then try again.")}throw z}let X=p0();if($){F({subcommand:"up",services:X.map((z)=>({name:z.name,state:z.state,port:z.port,health:z.health}))});return}if(X.length>0)process.stderr.write(`
240
+ `+k3(X)+`
241
+ `);for(let z of X)process.stdout.write(`${z.name}=${z.state}:${z.port}
242
+ `);process.stderr.write(`
243
+ `+V(" Next: ")+O("midnight generate --network undeployed")+`
244
+ `)}async function u2($){let Z=D("Stopping local network...");try{if(G0("stop"),Z.stop("Local network stopped (containers preserved)"),$){F({subcommand:"stop",status:"stopped"});return}}catch(Q){throw Z.stop($0("Failed to stop local network")),Q}}async function g2($){let Z=D("Tearing down local network...");try{if(G0("down --volumes"),Z.stop("Local network removed (containers, networks, volumes)"),$){F({subcommand:"down",status:"removed"});return}}catch(Q){throw Z.stop($0("Failed to tear down local network")),Q}}async function l2($){let Z=p0();if($){F({subcommand:"status",services:Z.map((Q)=>({name:Q.name,state:Q.state,port:Q.port,health:Q.health}))});return}if(Z.length===0){process.stderr.write(`
245
+ `+A("Localnet Status")+`
246
+
247
+ `),process.stderr.write(V(" No services running.")+`
248
+ `),process.stderr.write(V(" Run ")+O("midnight localnet up")+V(" to start.")+`
249
+
250
+ `);return}process.stderr.write(`
251
+ `+A("Localnet Status")+`
252
+
253
+ `),process.stderr.write(k3(Z)+`
254
+ `),process.stderr.write(`
255
+ `+y()+`
256
+
257
+ `);for(let Q of Z)process.stdout.write(`${Q.name}=${Q.state}:${Q.port}
258
+ `)}async function d2($){let Z=D("Removing conflicting containers...");try{try{G0("down")}catch{}let Q=w3();if(Q.length>0)Z.stop(`Removed ${Q.length} container${Q.length>1?"s":""}: ${Q.join(", ")}`);else Z.stop("No conflicting containers found");if($){F({subcommand:"clean",status:"cleaned",removed:Q});return}}catch(Q){throw Z.stop($0("Failed to clean up")),Q}}async function i2(){let $=G1(),Z=p2("docker",["compose","-f",$,"logs","-f"],{stdio:"inherit"});return new Promise((Q,X)=>{Z.on("close",(z)=>{if(z===0||z===130||z===null)Q();else X(new Error(`docker compose logs exited with code ${z}`))}),Z.on("error",X)})}async function h3($){let Z=$.subcommand;if(!Z||!c2(Z))throw new Error(`Usage: midnight localnet <${S3.join("|")}>
259
+
260
+ Subcommands:
261
+ up Start the local network
262
+ stop Stop containers (preserves state)
263
+ down Remove containers, networks, volumes
264
+ status Show service status
265
+ logs Stream service logs
266
+ clean Remove conflicting containers
267
+
268
+ Example: midnight localnet up`);N3();let Q=L($,"json");switch(process.stderr.write(`
269
+ `+A("Localnet")+`
270
+
271
+ `),Z){case"up":return m2(Q);case"stop":return u2(Q);case"down":return g2(Q);case"status":return l2(Q);case"logs":return i2();case"clean":return d2(Q)}}var S3;var p3=M(()=>{b3();N();q0();S3=["up","stop","down","status","logs","clean"]});import{Server as o2}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as n2}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as a2,CallToolRequestSchema as t2}from"@modelcontextprotocol/sdk/types.js";async function I($,Z,Q){let X=[];u0((q)=>X.push(q));let z=process.stderr.write;process.stderr.write=()=>!0;try{Z.flags.json=!0,await $(Z,Q);let q=X.join("").trim();if(!q)return{};return JSON.parse(q)}finally{u0(null),process.stderr.write=z}}var f={INVALID_ARGS:"INVALID_ARGS",WALLET_NOT_FOUND:"WALLET_NOT_FOUND",NETWORK_ERROR:"NETWORK_ERROR",INSUFFICIENT_BALANCE:"INSUFFICIENT_BALANCE",TX_REJECTED:"TX_REJECTED",STALE_UTXO:"STALE_UTXO",PROOF_TIMEOUT:"PROOF_TIMEOUT",DUST_REQUIRED:"DUST_REQUIRED",CANCELLED:"CANCELLED",UNKNOWN:"UNKNOWN"};function U1($){let Z=($.message??"").toLowerCase();if(Z.includes("operation cancelled")||Z.includes("operation aborted")||Z==="cancelled"||Z==="aborted")return{exitCode:7,errorCode:f.CANCELLED};if(Z.includes("wallet file not found")||Z.includes("wallet")&&Z.includes("not found"))return{exitCode:3,errorCode:f.WALLET_NOT_FOUND};if(Z.includes("missing required flag")||Z.includes("missing amount")||Z.includes("missing recipient")||Z.includes("missing config key")||Z.includes("missing or invalid subcommand")||Z.includes("unknown command")||Z.includes("cannot specify both")||Z.includes("invalid bip-39")||Z.includes("seed must be")||Z.includes("key index must be")||Z.includes("usage:"))return{exitCode:2,errorCode:f.INVALID_ARGS};if(Z.includes("proof")&&Z.includes("timeout"))return{exitCode:6,errorCode:f.PROOF_TIMEOUT};if(Z.includes("stale utxo")||Z.includes("error code 115")||Z.includes("errorcode: 115"))return{exitCode:6,errorCode:f.STALE_UTXO};if(Z.includes("no dust")||Z.includes("dust")&&(Z.includes("required")||Z.includes("available")||Z.includes("insufficient")))return{exitCode:5,errorCode:f.DUST_REQUIRED};if(Z.includes("insufficient")||Z.includes("not enough"))return{exitCode:5,errorCode:f.INSUFFICIENT_BALANCE};if(Z.includes("rejected")||Z.includes("transaction failed"))return{exitCode:6,errorCode:f.TX_REJECTED};if(Z.includes("econnrefused")||Z.includes("enotfound")||Z.includes("etimedout")||Z.includes("websocket")||Z.includes("connection refused")||Z.includes("network")&&Z.includes("error"))return{exitCode:4,errorCode:f.NETWORK_ERROR};return{exitCode:1,errorCode:f.UNKNOWN}}var L0={name:"midnight-wallet-cli",version:"0.1.8",type:"module",description:"Git-style CLI wallet for the Midnight blockchain",license:"Apache-2.0",bin:{midnight:"dist/wallet.js",mn:"dist/wallet.js","midnight-wallet-cli":"dist/wallet.js","midnight-wallet-mcp":"dist/mcp-server.js"},files:["dist"],scripts:{wallet:"tsx src/wallet.ts",build:'bun build src/wallet.ts --outfile dist/wallet.js --target node --format esm --packages external --minify --banner "#!/usr/bin/env node" && bun build src/mcp-server.ts --outfile dist/mcp-server.js --target node --format esm --packages external --minify --banner "#!/usr/bin/env node"',mcp:"tsx src/mcp-server.ts",prepublishOnly:"npm run build && npm run test",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit"},dependencies:{"@midnight-ntwrk/ledger-v7":"7.0.0","@midnight-ntwrk/midnight-js-network-id":"3.0.0","@midnight-ntwrk/midnight-js-types":"3.0.0","@midnight-ntwrk/wallet-sdk-abstractions":"1.0.0","@midnight-ntwrk/wallet-sdk-address-format":"3.0.0","@midnight-ntwrk/wallet-sdk-dust-wallet":"1.0.0","@midnight-ntwrk/wallet-sdk-facade":"1.0.0","@midnight-ntwrk/wallet-sdk-hd":"3.0.0","@midnight-ntwrk/wallet-sdk-shielded":"1.0.0","@midnight-ntwrk/wallet-sdk-unshielded-wallet":"1.0.0","@modelcontextprotocol/sdk":"^1.27.1","@scure/bip39":"^2.0.1",rxjs:"^7.8.1",ws:"^8.19.0"},devDependencies:{"@types/node":"^22.19.13","@types/ws":"^8.18.1",tsx:"^4.21.0",typescript:"^5.9.3",vitest:"^3.2.4"}};var Y$=L0.name,j1=L0.version,G$=L0.description;function m($,Z,Q){let X={json:!0},z=[];for(let[q,Y]of Object.entries(Z)){if(Y===void 0||Y===null)continue;if(typeof Y==="boolean"){if(Y)X[q]=!0}else X[q]=String(Y)}return{command:$,subcommand:Q,positionals:z,flags:X}}var r2={generate:()=>Promise.resolve().then(() => (g1(),u1)),info:()=>Promise.resolve().then(() => (i1(),d1)),balance:()=>Promise.resolve().then(() => (s1(),r1)),address:()=>Promise.resolve().then(() => (Z3(),$3)),"genesis-address":()=>Promise.resolve().then(() => (z3(),X3)),"inspect-cost":()=>Promise.resolve().then(() => (J3(),G3)),airdrop:()=>Promise.resolve().then(() => (F3(),V3)),transfer:()=>Promise.resolve().then(() => (M3(),P3)),dust:()=>Promise.resolve().then(() => (A3(),y3)),config:()=>Promise.resolve().then(() => (R3(),T3)),localnet:()=>Promise.resolve().then(() => (p3(),f3))};async function T($){let Z=r2[$];if(!Z)throw new Error(`Unknown command handler: ${$}`);return(await Z()).default}var c3=[{name:"midnight_generate",description:"Generate a new wallet (random mnemonic, or restore from seed/mnemonic)",inputSchema:{type:"object",properties:{network:{type:"string",description:"Network: preprod, preview, undeployed",enum:["preprod","preview","undeployed"]},seed:{type:"string",description:"Restore from existing seed (64-char hex)"},mnemonic:{type:"string",description:"Restore from BIP-39 mnemonic (24 words)"},output:{type:"string",description:"Custom output path (default: ~/.midnight/wallet.json)"},force:{type:"string",description:'Set to "true" to overwrite existing wallet file'}}},async handler($){let Z=m("generate",$);if($.force==="true"||$.force===!0)Z.flags.force=!0;let Q=await T("generate");return I(Q,Z)}},{name:"midnight_info",description:"Display wallet address, network, creation date (no secrets shown)",inputSchema:{type:"object",properties:{wallet:{type:"string",description:"Custom wallet file path"}}},async handler($){let Z=m("info",$),Q=await T("info");return I(Q,Z)}},{name:"midnight_balance",description:"Check unshielded balance via indexer subscription",inputSchema:{type:"object",properties:{address:{type:"string",description:"Address to check (or reads from wallet file)"},wallet:{type:"string",description:"Custom wallet file path"},network:{type:"string",description:"Override network detection",enum:["preprod","preview","undeployed"]},"indexer-ws":{type:"string",description:"Custom indexer WebSocket URL"}}},async handler($){let Z=$.address,Q=m("balance",$,Z);delete Q.flags.address;let X=await T("balance");return I(X,Q)}},{name:"midnight_address",description:"Derive and display an unshielded address from a seed",inputSchema:{type:"object",properties:{seed:{type:"string",description:"Seed to derive from (required, 64-char hex)"},network:{type:"string",description:"Network for address prefix",enum:["preprod","preview","undeployed"]},index:{type:"string",description:"Key derivation index (default: 0)"}},required:["seed"]},async handler($){let Z=m("address",$),Q=await T("address");return I(Q,Z)}},{name:"midnight_genesis_address",description:"Display the genesis wallet address (seed 0x01) for a network",inputSchema:{type:"object",properties:{network:{type:"string",description:"Network for address prefix",enum:["preprod","preview","undeployed"]}}},async handler($){let Z=m("genesis-address",$),Q=await T("genesis-address");return I(Q,Z)}},{name:"midnight_inspect_cost",description:"Display current block limits derived from LedgerParameters",inputSchema:{type:"object",properties:{}},async handler(){let $=m("inspect-cost",{}),Z=await T("inspect-cost");return I(Z,$)}},{name:"midnight_airdrop",description:"Fund your wallet from the genesis wallet (undeployed network only)",inputSchema:{type:"object",properties:{amount:{type:"string",description:"Amount in NIGHT to airdrop"},wallet:{type:"string",description:"Custom wallet file path"}},required:["amount"]},async handler($){let Z=$.amount,Q=m("airdrop",$,Z);delete Q.flags.amount;let X=await T("airdrop");return I(X,Q)}},{name:"midnight_transfer",description:"Send NIGHT tokens to another address",inputSchema:{type:"object",properties:{to:{type:"string",description:"Recipient bech32m address"},amount:{type:"string",description:"Amount in NIGHT to send"},wallet:{type:"string",description:"Custom wallet file path"}},required:["to","amount"]},async handler($){let{to:Z,amount:Q}=$,X=m("transfer",$,Z);X.positionals=[Q],delete X.flags.to,delete X.flags.amount;let z=await T("transfer");return I(z,X)}},{name:"midnight_dust_register",description:"Register NIGHT UTXOs for dust (fee token) generation",inputSchema:{type:"object",properties:{wallet:{type:"string",description:"Custom wallet file path"}}},async handler($){let Z=m("dust",$,"register"),Q=await T("dust");return I(Q,Z)}},{name:"midnight_dust_status",description:"Check dust registration status and balance",inputSchema:{type:"object",properties:{wallet:{type:"string",description:"Custom wallet file path"}}},async handler($){let Z=m("dust",$,"status"),Q=await T("dust");return I(Q,Z)}},{name:"midnight_config_get",description:"Read a persistent config value",inputSchema:{type:"object",properties:{key:{type:"string",description:'Config key to read (e.g. "network")'}},required:["key"]},async handler($){let Q={command:"config",subcommand:"get",positionals:[$.key],flags:{json:!0}},X=await T("config");return I(X,Q)}},{name:"midnight_config_set",description:"Write a persistent config value",inputSchema:{type:"object",properties:{key:{type:"string",description:'Config key to set (e.g. "network")'},value:{type:"string",description:"Config value to set"}},required:["key","value"]},async handler($){let{key:Z,value:Q}=$,X={command:"config",subcommand:"set",positionals:[Z,Q],flags:{json:!0}},z=await T("config");return I(z,X)}},{name:"midnight_localnet_up",description:"Start a local Midnight network via Docker Compose",inputSchema:{type:"object",properties:{}},async handler(){let $={command:"localnet",subcommand:"up",positionals:[],flags:{json:!0}},Z=await T("localnet");return I(Z,$)}},{name:"midnight_localnet_stop",description:"Stop local network containers (preserves state for fast restart)",inputSchema:{type:"object",properties:{}},async handler(){let $={command:"localnet",subcommand:"stop",positionals:[],flags:{json:!0}},Z=await T("localnet");return I(Z,$)}},{name:"midnight_localnet_down",description:"Remove local network containers, networks, and volumes (full teardown)",inputSchema:{type:"object",properties:{}},async handler(){let $={command:"localnet",subcommand:"down",positionals:[],flags:{json:!0}},Z=await T("localnet");return I(Z,$)}},{name:"midnight_localnet_status",description:"Show local network service status and ports",inputSchema:{type:"object",properties:{}},async handler(){let $={command:"localnet",subcommand:"status",positionals:[],flags:{json:!0}},Z=await T("localnet");return I(Z,$)}},{name:"midnight_localnet_clean",description:"Remove conflicting containers from other setups",inputSchema:{type:"object",properties:{}},async handler(){let $={command:"localnet",subcommand:"clean",positionals:[],flags:{json:!0}},Z=await T("localnet");return I(Z,$)}}],J1=new o2({name:"midnight-wallet-cli",version:j1},{capabilities:{tools:{}}});J1.setRequestHandler(a2,async()=>{return{tools:c3.map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}});J1.setRequestHandler(t2,async($)=>{let{name:Z,arguments:Q}=$.params,X=c3.find((z)=>z.name===Z);if(!X)return{content:[{type:"text",text:`Unknown tool: ${Z}`}],isError:!0};try{let z=await X.handler(Q??{});return{content:[{type:"text",text:JSON.stringify(z,null,2)}]}}catch(z){let q=z instanceof Error?z:new Error(String(z)),{errorCode:Y}=U1(q);return{content:[{type:"text",text:JSON.stringify({error:!0,code:Y,message:q.message})}],isError:!0}}});async function s2(){let $=new n2;await J1.connect($)}s2().catch(($)=>{process.stderr.write(`MCP server error: ${$.message}
272
+ `),process.exit(1)});