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