nansen-cli 1.44.3 → 1.46.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/src/cli.js CHANGED
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  import { NansenAPI, NansenError, CommandError, ErrorCode, saveConfig, deleteConfig, getConfigFile, clearCache, getCacheDir, validateAddress, normalizeAddress, sleep } from './api.js';
7
- import { buildWalletCommands } from './wallet.js';
7
+ import { buildWalletCommands, WALLET_SUBCOMMANDS } from './wallet.js';
8
8
  import { buildBridgeCommands, formatBridgeRoutes } from './bridge.js';
9
9
  import { buildPerpCommands } from './perp.js';
10
10
  import { buildTradingCommands } from './trading.js';
@@ -14,7 +14,7 @@ import { buildAgentCommands } from './commands/agent.js';
14
14
  import { buildMcpCommands } from './commands/mcp.js';
15
15
  import { buildCompletionCommands } from './commands/completion.js';
16
16
  import { buildResearchCommands, RESEARCH_HISTORICAL_SUBCOMMANDS, RESEARCH_SUBCOMMANDS } from './commands/research.js';
17
- import { buildPagination, parseSort } from './query-options.js';
17
+ import { buildPagination, parseSort, parseCsvOption, rejectBlankOption, parseObjectOption } from './query-options.js';
18
18
  export { buildPagination, parseSort };
19
19
  import { resolveAddress, isEnsName } from './ens.js';
20
20
  import { compareSemver } from './semver.js';
@@ -49,36 +49,53 @@ export const SCHEMA = { version: VERSION, ...schemaDefinition };
49
49
  * Returns true/false/undefined (undefined = not supplied).
50
50
  */
51
51
  export function resolveBooleanOption(options, flags, key) {
52
- if (options[key] !== undefined) {
53
- const val = String(options[key]).toLowerCase();
52
+ const optionValue = options[key];
53
+ const flagValue = flags[key];
54
+
55
+ if (Array.isArray(optionValue) || Array.isArray(flagValue) ||
56
+ (optionValue !== undefined && flagValue !== undefined)) {
57
+ throw new NansenError(`--${key} cannot be repeated`, ErrorCode.INVALID_PARAMS);
58
+ }
59
+ if (optionValue !== undefined) {
60
+ const val = String(optionValue).toLowerCase();
54
61
  if (val === 'true' || val === '1') return true;
55
62
  if (val === 'false' || val === '0') return false;
63
+ throw new NansenError(`--${key} must be true or false`, ErrorCode.INVALID_PARAMS);
56
64
  }
57
- if (flags[key] !== undefined) return Boolean(flags[key]);
65
+ if (flagValue !== undefined) return Boolean(flagValue);
58
66
  return undefined;
59
67
  }
60
68
 
61
69
  // ============= Field Filtering =============
62
70
 
63
71
  /**
64
- * Filter object to include only specified fields
65
- * Supports nested paths with dot notation (e.g., "data.results")
72
+ * Filter object to include only specified fields.
73
+ *
74
+ * A bare name ("address") matches that key at any depth. A dotted path
75
+ * ("data.results", "results.address") matches only at that position, counted
76
+ * from the root of the payload; array elements do not add a segment, so
77
+ * "results.address" selects `address` inside each item of `results`.
66
78
  */
67
79
  export function filterFields(data, fields) {
68
80
  if (!fields || fields.length === 0) return data;
69
81
 
70
- const fieldSet = new Set(fields);
82
+ const names = new Set();
83
+ const paths = new Set();
84
+ for (const field of fields) {
85
+ (field.includes('.') ? paths : names).add(field);
86
+ }
71
87
 
72
- function filterObject(obj) {
88
+ function filterObject(obj, path) {
73
89
  if (obj === null || obj === undefined) return obj;
74
90
  if (Array.isArray(obj)) {
75
- return obj.map(item => filterObject(item));
91
+ return obj.map(item => filterObject(item, path));
76
92
  }
77
93
  if (typeof obj !== 'object') return obj;
78
94
 
79
95
  const filtered = {};
80
96
  for (const key of Object.keys(obj)) {
81
- if (fieldSet.has(key)) {
97
+ const keyPath = path ? `${path}.${key}` : key;
98
+ if (names.has(key) || paths.has(keyPath)) {
82
99
  // Explicitly requested — include as-is
83
100
  filtered[key] = obj[key];
84
101
  } else if (typeof obj[key] === 'object' && obj[key] !== null) {
@@ -89,7 +106,7 @@ export function filterFields(data, fields) {
89
106
  const hasObjectElements = obj[key].length > 0 &&
90
107
  typeof obj[key][0] === 'object' && obj[key][0] !== null;
91
108
  if (hasObjectElements) {
92
- const nested = obj[key].map(item => filterObject(item))
109
+ const nested = obj[key].map(item => filterObject(item, keyPath))
93
110
  .filter(item => Object.keys(item).length > 0);
94
111
  if (nested.length > 0) {
95
112
  filtered[key] = nested;
@@ -97,7 +114,7 @@ export function filterFields(data, fields) {
97
114
  }
98
115
  } else {
99
116
  // Plain object — always recurse in case it wraps requested fields
100
- const nested = filterObject(obj[key]);
117
+ const nested = filterObject(obj[key], keyPath);
101
118
  if (nested !== null && nested !== undefined && Object.keys(nested).length > 0) {
102
119
  filtered[key] = nested;
103
120
  }
@@ -107,14 +124,17 @@ export function filterFields(data, fields) {
107
124
  return filtered;
108
125
  }
109
126
 
110
- return filterObject(data);
127
+ return filterObject(data, '');
111
128
  }
112
129
 
113
130
  /**
114
131
  * Parse comma-separated fields string
115
132
  */
116
133
  export function parseFields(fieldsOption) {
117
- if (!fieldsOption) return null;
134
+ if (fieldsOption === undefined || fieldsOption === '') return null;
135
+ if (typeof fieldsOption !== 'string') {
136
+ throw new NansenError('--fields must be a comma-separated string', ErrorCode.INVALID_PARAMS);
137
+ }
118
138
  return fieldsOption.split(',').map(f => f.trim()).filter(f => f.length > 0);
119
139
  }
120
140
 
@@ -171,33 +191,70 @@ export const VALUELESS_FLAGS = new Set([
171
191
  'pretty', 'help', 'version', 'table', 'no-retry', 'cache', 'no-cache', 'stream',
172
192
  'enrich', 'full', 'human', 'enabled', 'disabled', 'expert', 'json', 'offline',
173
193
  'no-simulate', 'no-verify-outcome', 'no-revoke-excessive-allowance', 'dry-run',
174
- 'send-api-key',
194
+ 'send-api-key', 'all', 'max', 'gasless', 'auto-slippage', 'unsafe-no-password',
195
+ 'reveal', 'yes',
175
196
  ]);
176
197
 
177
198
  export function parseArgs(args) {
178
199
  const result = { _: [], flags: {}, options: {} };
200
+
201
+ const addFlag = (key) => {
202
+ if (key in result.flags) {
203
+ if (!Array.isArray(result.flags[key])) result.flags[key] = [result.flags[key]];
204
+ result.flags[key].push(true);
205
+ } else {
206
+ result.flags[key] = true;
207
+ }
208
+ };
179
209
 
180
210
  for (let i = 0; i < args.length; i++) {
181
211
  const arg = args[i];
182
212
 
183
213
  if (arg.startsWith('--')) {
184
- const key = arg.slice(2);
185
- const next = args[i + 1];
214
+ const equalsIndex = arg.indexOf('=');
215
+ const inlineKey = equalsIndex === -1 ? null : arg.slice(2, equalsIndex);
216
+ // `--help=false` is neither help nor a meaningful false value: valueless
217
+ // switches only accept their bare spelling. Reject it instead of leaking
218
+ // a stale `flags['help=false']` key that no handler will ever inspect.
219
+ if (inlineKey !== null && VALUELESS_FLAGS.has(inlineKey)) {
220
+ throw new NansenError(`--${inlineKey} does not accept a value`, ErrorCode.INVALID_PARAMS);
221
+ }
222
+ // Value-taking options, including boolean options handled by
223
+ // resolveBooleanOption(), accept the conventional `--key=value` spelling.
224
+ const hasInlineValue = inlineKey !== null;
225
+ const key = hasInlineValue ? inlineKey : arg.slice(2);
226
+ const next = hasInlineValue ? arg.slice(equalsIndex + 1) : args[i + 1];
186
227
 
187
228
  if (VALUELESS_FLAGS.has(key)) {
229
+ // Repeating a switch is idempotent. Keeping the value strictly true
230
+ // avoids leaking `[true, true]` into consumers that use `=== true`.
188
231
  result.flags[key] = true;
189
- } else if (next && (!next.startsWith('-') || /^-\d/.test(next))) {
190
- // Try to parse as JSON first (for objects/arrays/booleans),
191
- // but keep numeric strings as strings to avoid precision loss
192
- // and scientific notation for large integers (e.g. 1e+21).
193
- let parsedValue;
232
+ // `next !== undefined` rather than a truthiness check: an explicit empty
233
+ // string is a real value, and skipping it here left `""` dangling to be
234
+ // picked up as a positional arg on the next iteration.
235
+ // An inline value was explicitly supplied and is always consumed, even
236
+ // when it begins with a dash; downstream option validation owns whether
237
+ // that value is meaningful. The dash guard applies only to two-token
238
+ // input, where `--key --next` denotes two separate arguments.
239
+ } else if (hasInlineValue || (next !== undefined && (!next.startsWith('-') || /^-\d/.test(next)))) {
240
+ // Try to parse as JSON so object/array options (`--filters '{}'`,
241
+ // `--order-by '[...]'`) arrive structured. Numbers stay strings to
242
+ // avoid precision loss and scientific notation for large integers
243
+ // (e.g. 1e+21). The bare keywords true/false/null stay strings too:
244
+ // no option takes a boolean or null *value*, so coercing them would
245
+ // silently retype a string option (`--sort true` used to become the
246
+ // boolean true). Boolean options read the strings 'true'/'false'
247
+ // through resolveBooleanOption().
248
+ let parsedValue = next;
194
249
  try {
195
250
  const parsed = JSON.parse(next);
196
- parsedValue = typeof parsed === 'number' ? next : parsed;
251
+ if (typeof parsed !== 'number' && typeof parsed !== 'boolean' && parsed !== null) {
252
+ parsedValue = parsed;
253
+ }
197
254
  } catch {
198
- parsedValue = next;
255
+ // Not JSON: keep the raw string.
199
256
  }
200
- i++;
257
+ if (!hasInlineValue) i++;
201
258
  // Accumulate repeated options into arrays (supports repeatable flags like --token, --subject)
202
259
  if (key in result.options) {
203
260
  if (!Array.isArray(result.options[key])) {
@@ -208,10 +265,10 @@ export function parseArgs(args) {
208
265
  result.options[key] = parsedValue;
209
266
  }
210
267
  } else {
211
- result.flags[key] = true;
268
+ addFlag(key);
212
269
  }
213
270
  } else if (arg.startsWith('-')) {
214
- result.flags[arg.slice(1)] = true;
271
+ addFlag(arg.slice(1));
215
272
  } else {
216
273
  result._.push(arg);
217
274
  }
@@ -220,15 +277,65 @@ export function parseArgs(args) {
220
277
  return result;
221
278
  }
222
279
 
223
- function parseNonNegativeSafeIntegerOption(name, options, flags, defaultValue) {
280
+ function parseSafeIntegerOption(
281
+ name,
282
+ options,
283
+ flags,
284
+ defaultValue,
285
+ requirement = 'safe integer',
286
+ ) {
224
287
  if (flags[name]) {
225
288
  throw new NansenError(
226
- `--${name} requires a non-negative safe integer value`,
289
+ `--${name} requires a ${requirement} value`,
227
290
  ErrorCode.INVALID_PARAMS,
228
291
  );
229
292
  }
293
+
230
294
  if (options[name] === undefined) return defaultValue;
231
295
 
296
+ const rawValue = options[name];
297
+
298
+ if (Array.isArray(rawValue)) {
299
+ throw new NansenError(
300
+ `--${name} may only be specified once`,
301
+ ErrorCode.INVALID_PARAMS,
302
+ );
303
+ }
304
+
305
+ if (
306
+ typeof rawValue === 'boolean' ||
307
+ (typeof rawValue === 'string' && rawValue.trim() === '')
308
+ ) {
309
+ throw new NansenError(
310
+ `--${name} requires a ${requirement} value`,
311
+ ErrorCode.INVALID_PARAMS,
312
+ );
313
+ }
314
+
315
+ const value =
316
+ typeof rawValue === 'string' || typeof rawValue === 'number'
317
+ ? Number(rawValue)
318
+ : NaN;
319
+
320
+ if (!Number.isSafeInteger(value)) {
321
+ throw new NansenError(
322
+ `--${name} must be a ${requirement}; received: ${String(rawValue)}`,
323
+ ErrorCode.INVALID_PARAMS,
324
+ );
325
+ }
326
+
327
+ return value;
328
+ }
329
+
330
+ function parseFiniteNumberOption(name, options, flags) {
331
+ if (flags[name]) {
332
+ throw new NansenError(
333
+ `--${name} requires a finite number`,
334
+ ErrorCode.INVALID_PARAMS,
335
+ );
336
+ }
337
+ if (options[name] === undefined) return undefined;
338
+
232
339
  const rawValue = options[name];
233
340
  if (Array.isArray(rawValue)) {
234
341
  throw new NansenError(
@@ -238,22 +345,56 @@ function parseNonNegativeSafeIntegerOption(name, options, flags, defaultValue) {
238
345
  }
239
346
  if (typeof rawValue === 'string' && rawValue.trim() === '') {
240
347
  throw new NansenError(
241
- `--${name} requires a non-negative safe integer value`,
348
+ `--${name} requires a finite number`,
242
349
  ErrorCode.INVALID_PARAMS,
243
350
  );
244
351
  }
245
352
  const value = typeof rawValue === 'string' || typeof rawValue === 'number'
246
353
  ? Number(rawValue)
247
354
  : NaN;
248
- if (!Number.isSafeInteger(value) || value < 0) {
355
+ if (!Number.isFinite(value)) {
249
356
  throw new NansenError(
250
- `--${name} must be a non-negative safe integer; received: ${String(rawValue)}`,
357
+ `--${name} must be a finite number; received: ${String(rawValue)}`,
251
358
  ErrorCode.INVALID_PARAMS,
252
359
  );
253
360
  }
254
361
  return value;
255
362
  }
256
363
 
364
+ function parseNonNegativeSafeIntegerOption(name, options, flags, defaultValue) {
365
+ const value = parseSafeIntegerOption(
366
+ name,
367
+ options,
368
+ flags,
369
+ defaultValue,
370
+ 'non-negative safe integer',
371
+ );
372
+
373
+ if (value < 0) {
374
+ throw new NansenError(
375
+ `--${name} must be a non-negative safe integer; received: ${value}`,
376
+ ErrorCode.INVALID_PARAMS,
377
+ );
378
+ }
379
+
380
+ return value;
381
+ }
382
+
383
+
384
+ function parseDaysOption(options, flags) {
385
+ const days = parseNonNegativeSafeIntegerOption('days', options, flags, 30);
386
+ // Safe integers can still exceed JavaScript Date's representable range.
387
+ // Anchor the overflow check to the Unix epoch so the boundary is deterministic.
388
+ const fromMs = 0 - days * 24 * 60 * 60 * 1000;
389
+ if (Number.isNaN(new Date(fromMs).getTime())) {
390
+ throw new NansenError(
391
+ `--days is outside the supported date range; received: ${days}`,
392
+ ErrorCode.INVALID_PARAMS,
393
+ );
394
+ }
395
+ return days;
396
+ }
397
+
257
398
  // Format a single value for table display
258
399
  export function formatValue(val) {
259
400
  if (val === null || val === undefined) return '';
@@ -293,7 +434,7 @@ export function formatTable(data) {
293
434
  }
294
435
 
295
436
  // Get columns from first record, prioritize common useful fields
296
- const priorityFields = ['token_symbol', 'token_name', 'symbol', 'name', 'address', 'label', 'chain', 'value_usd', 'amount', 'pnl_usd', 'price_usd', 'volume_usd', 'net_flow_usd', 'timestamp', 'block_timestamp'];
437
+ const priorityFields = ['token_symbol', 'token_name', 'symbol', 'name', 'wallet_address', 'address', 'label', 'chain', 'value_usd', 'amount', 'pnl_usd', 'price_usd', 'volume_usd', 'net_flow_usd', 'timestamp', 'block_timestamp'];
297
438
  const allKeys = [...new Set(records.flatMap(r => Object.keys(r)))];
298
439
 
299
440
  // Sort: priority fields first, then alphabetically
@@ -379,21 +520,30 @@ export function formatCsv(data) {
379
520
  return lines.join('\n');
380
521
  }
381
522
 
523
+ // Render the error envelope for the non-JSON formats. CSV gets a real header
524
+ // row plus one record so the envelope stays machine-parseable; table keeps the
525
+ // leading `Error:` line and follows it with one `key: value` line per field, so
526
+ // code, status and details are not dropped on the way to the terminal.
527
+ function formatErrorText(data, { csv = false } = {}) {
528
+ if (csv) return formatCsv(data);
529
+ const lines = [`Error: ${data.error}`];
530
+ for (const [key, val] of Object.entries(data)) {
531
+ if (key === 'success' || key === 'error' || val == null) continue;
532
+ lines.push(`${key}: ${typeof val === 'object' ? JSON.stringify(val) : val}`);
533
+ }
534
+ return lines.join('\n');
535
+ }
536
+
382
537
  // Format output data (returns string, does not print)
383
538
  export function formatOutput(data, { pretty = false, table = false, csv = false } = {}) {
384
- if (csv) {
539
+ if (csv || table) {
385
540
  if (data.success === false) {
386
- return { type: 'error', text: `Error: ${data.error}` };
387
- }
388
- const csvData = data.data || data;
389
- return { type: 'csv', text: formatCsv(csvData) };
390
- } else if (table) {
391
- if (data.success === false) {
392
- return { type: 'error', text: `Error: ${data.error}` };
393
- } else {
394
- const tableData = data.data || data;
395
- return { type: 'table', text: formatTable(tableData) };
541
+ return { type: 'error', text: formatErrorText(data, { csv }) };
396
542
  }
543
+ const body = data.data || data;
544
+ return csv
545
+ ? { type: 'csv', text: formatCsv(body) }
546
+ : { type: 'table', text: formatTable(body) };
397
547
  } else if (pretty) {
398
548
  return { type: 'json', text: JSON.stringify(data, null, 2) };
399
549
  } else {
@@ -410,6 +560,10 @@ export const USAGE_ERROR_CODES = new Set(['MISSING_PARAM', 'MISSING_ARGS']);
410
560
 
411
561
  export function isUsageError(errorData, { pretty, table, csv, stream, isTTY }) {
412
562
  if (!USAGE_ERROR_CODES.has(errorData.code)) return false;
563
+ // API errors can map onto the same semantic code (for example the server's
564
+ // `missing_field` becomes MISSING_PARAM), but they are not local usage
565
+ // banners and must retain the structured envelope in every output mode.
566
+ if (errorData.status != null) return false;
413
567
  if (pretty || table || csv || stream) return false;
414
568
  return !!isTTY;
415
569
  }
@@ -468,23 +622,51 @@ export function formatStream(data) {
468
622
  * or already-parsed object {from, to}.
469
623
  * Falls back to days-based range if no date provided.
470
624
  */
471
- export function parseDateOption(dateOption, days = 30) {
472
- if (dateOption) {
473
- if (typeof dateOption === 'object' && dateOption.from) {
474
- return dateOption;
625
+ function isValidDateOnly(value) {
626
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
627
+ const parsed = new Date(`${value}T00:00:00.000Z`);
628
+ return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
629
+ }
630
+
631
+ export function parseDateOption(dateOption, days = 30, valuelessDateFlag = false) {
632
+ if (valuelessDateFlag) {
633
+ throw new NansenError(
634
+ '--date requires a value in YYYY-MM-DD format or a JSON date range',
635
+ ErrorCode.INVALID_PARAMS,
636
+ );
637
+ }
638
+
639
+ if (dateOption === undefined) {
640
+ // Default: use days-based range only when --date was not supplied.
641
+ const to = new Date().toISOString().split('T')[0];
642
+ const from = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
643
+ return { from, to };
644
+ }
645
+
646
+ let parsedOption = dateOption;
647
+ if (typeof parsedOption === 'string' && !isValidDateOnly(parsedOption)) {
648
+ try {
649
+ parsedOption = JSON.parse(parsedOption);
650
+ } catch {
651
+ // Keep the original value so the actionable validation error below is used.
475
652
  }
476
- if (typeof dateOption === 'string') {
477
- // Simple date string: use as both from and to
478
- const dateMatch = dateOption.match(/^\d{4}-\d{2}-\d{2}$/);
479
- if (dateMatch) {
480
- return { from: dateOption, to: dateOption };
481
- }
653
+ }
654
+
655
+ if (typeof parsedOption === 'string' && isValidDateOnly(parsedOption)) {
656
+ return { from: parsedOption, to: parsedOption };
657
+ }
658
+
659
+ if (parsedOption && typeof parsedOption === 'object' && !Array.isArray(parsedOption)) {
660
+ const { from, to } = parsedOption;
661
+ if (isValidDateOnly(from) && (to === undefined || isValidDateOnly(to))) {
662
+ return { from, to: to ?? from };
482
663
  }
483
664
  }
484
- // Default: use days-based range
485
- const to = new Date().toISOString().split('T')[0];
486
- const from = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
487
- return { from, to };
665
+
666
+ throw new NansenError(
667
+ '--date must be YYYY-MM-DD or a JSON object with a valid "from" date and optional "to" date',
668
+ ErrorCode.INVALID_PARAMS,
669
+ );
488
670
  }
489
671
 
490
672
  // Enrich transfers with Nansen labels for from/to addresses
@@ -553,6 +735,35 @@ export function parseAddressList(raw) {
553
735
  }
554
736
  }
555
737
 
738
+ /**
739
+ * Read an address list from a file: either a JSON array of address strings or
740
+ * one address per line. Shared by the profiler commands that accept --file.
741
+ */
742
+ function readAddressFile(file) {
743
+ let content;
744
+ try {
745
+ content = fs.readFileSync(file, 'utf8');
746
+ } catch (err) {
747
+ throw new NansenError(
748
+ `Could not read --file ${file}: ${err.code === 'ENOENT' ? 'no such file' : err.message}`,
749
+ ErrorCode.INVALID_PARAMS
750
+ );
751
+ }
752
+ try {
753
+ const parsed = JSON.parse(content);
754
+ if (!Array.isArray(parsed) || !parsed.every(item => typeof item === 'string')) {
755
+ throw new NansenError(
756
+ 'File must contain a JSON array of address strings or one address per line',
757
+ ErrorCode.INVALID_PARAMS
758
+ );
759
+ }
760
+ return parsed.map(a => a.trim()).filter(Boolean);
761
+ } catch (e) {
762
+ if (e instanceof NansenError) throw e;
763
+ return content.split('\n').map(a => a.trim()).filter(Boolean);
764
+ }
765
+ }
766
+
556
767
  // ============= Composite Functions =============
557
768
 
558
769
  export async function batchProfile(api, params = {}) {
@@ -606,6 +817,17 @@ export async function batchProfile(api, params = {}) {
606
817
  return { results, total: addresses.length, completed: results.filter(r => !r.error).length };
607
818
  }
608
819
 
820
+ function normalizeTraceDepth(raw) {
821
+ const value = parseSafeIntegerOption(
822
+ 'depth',
823
+ { depth: raw },
824
+ {},
825
+ 2,
826
+ );
827
+
828
+ return Math.max(1, Math.min(value, 5));
829
+ }
830
+
609
831
  export async function traceCounterparties(api, params = {}) {
610
832
  let { address, chain = 'ethereum', depth = 2, width = 10, days = 30, delayMs = 1000 } = params;
611
833
  if (!address) {
@@ -626,7 +848,7 @@ export async function traceCounterparties(api, params = {}) {
626
848
  if (!validation.valid) {
627
849
  throw new NansenError(validation.error, ErrorCode.INVALID_ADDRESS);
628
850
  }
629
- const clampedDepth = Math.max(1, Math.min(depth, 5));
851
+ const clampedDepth = normalizeTraceDepth(depth);
630
852
  const visited = new Set();
631
853
  const nodes = [];
632
854
  const edges = [];
@@ -691,47 +913,102 @@ export async function compareWallets(api, params = {}) {
691
913
  }
692
914
  }
693
915
 
694
- // Fetch counterparties and balances for both addresses
916
+ // Fetch counterparties and balances for both addresses. A failed request is
917
+ // recorded rather than treated as an empty result, so an auth or rate-limit
918
+ // error cannot masquerade as "no overlap" / "0 USD".
919
+ const settle = (promise) => promise.then(value => ({ value }), error => ({ error }));
695
920
  const [cp1, cp2] = await Promise.all([
696
- api.addressCounterparties({ address: addr1, chain, days }).catch(() => null),
697
- api.addressCounterparties({ address: addr2, chain, days }).catch(() => null),
921
+ settle(api.addressCounterparties({ address: addr1, chain, days })),
922
+ settle(api.addressCounterparties({ address: addr2, chain, days })),
698
923
  ]);
699
924
  await sleep(delayMs);
700
925
  const [bal1, bal2] = await Promise.all([
701
- api.addressBalance({ address: addr1, chain }).catch(() => null),
702
- api.addressBalance({ address: addr2, chain }).catch(() => null),
926
+ settle(api.addressBalance({ address: addr1, chain })),
927
+ settle(api.addressBalance({ address: addr2, chain })),
703
928
  ]);
704
929
 
930
+ const outcomes = [
931
+ [addr1, 'counterparties', cp1], [addr2, 'counterparties', cp2],
932
+ [addr1, 'balance', bal1], [addr2, 'balance', bal2],
933
+ ];
934
+ const errors = [];
935
+ const failures = [];
936
+ for (const [address, source, outcome] of outcomes) {
937
+ if (outcome.error) {
938
+ failures.push(outcome.error);
939
+ errors.push({ address, source, code: outcome.error.code ?? 'UNKNOWN', message: outcome.error.message });
940
+ }
941
+ }
942
+ if (failures.length === outcomes.length) {
943
+ throw failures[0];
944
+ }
945
+
705
946
  // Extract counterparty addresses
706
947
  const extractCps = (result) => {
707
948
  const list = result?.data?.results || result?.counterparties || result?.data || [];
708
949
  return Array.isArray(list) ? list : [];
709
950
  };
710
- const cps1 = extractCps(cp1);
711
- const cps2 = extractCps(cp2);
712
- const cpAddrs1 = new Set(cps1.map(c => c.counterparty_address || c.address || c.counterparty).filter(Boolean));
713
- const cpAddrs2 = new Set(cps2.map(c => c.counterparty_address || c.address || c.counterparty).filter(Boolean));
714
- const sharedCpAddrs = [...cpAddrs1].filter(a => cpAddrs2.has(a));
951
+ let sharedCpAddrs = null;
952
+ if (!cp1.error && !cp2.error) {
953
+ const cpAddrs1 = new Set(extractCps(cp1.value).map(c => c.counterparty_address || c.address || c.counterparty).filter(Boolean));
954
+ const cpAddrs2 = new Set(extractCps(cp2.value).map(c => c.counterparty_address || c.address || c.counterparty).filter(Boolean));
955
+ sharedCpAddrs = [...cpAddrs1].filter(a => cpAddrs2.has(a));
956
+ }
715
957
 
716
958
  // Extract token holdings
717
959
  const extractTokens = (result) => {
718
960
  const list = result?.data?.results || result?.balances || result?.data || [];
719
961
  return Array.isArray(list) ? list : [];
720
962
  };
721
- const tokens1 = extractTokens(bal1);
722
- const tokens2 = extractTokens(bal2);
723
- const tokenSyms1 = new Set(tokens1.map(t => t.token_symbol).filter(Boolean));
724
- const tokenSyms2 = new Set(tokens2.map(t => t.token_symbol).filter(Boolean));
725
- const sharedTokens = [...tokenSyms1].filter(s => tokenSyms2.has(s));
963
+ const tokens1 = bal1.error ? null : extractTokens(bal1.value);
964
+ const tokens2 = bal2.error ? null : extractTokens(bal2.value);
965
+ let sharedTokens = null;
966
+ if (tokens1 && tokens2) {
967
+ // Two different contracts can share a symbol, so when both sides report a
968
+ // token address the address decides. When either side has no address for
969
+ // a token (some responses omit it for the native asset) the symbol is the
970
+ // only identity available and is used instead.
971
+ const addressOf = (t) => {
972
+ const address = t.token_address || t.mint || t.address;
973
+ return address ? String(address).toLowerCase() : null;
974
+ };
975
+ const symbolOf = (t) => (t.token_symbol ? String(t.token_symbol).toLowerCase() : null);
976
+ const addresses2 = new Set(tokens2.map(addressOf).filter(Boolean));
977
+ const symbols2 = new Set(tokens2.map(symbolOf).filter(Boolean));
978
+ const symbolsWithoutAddress2 = new Set(
979
+ tokens2.filter(t => !addressOf(t)).map(symbolOf).filter(Boolean)
980
+ );
981
+ const seen = new Set();
982
+ sharedTokens = [];
983
+ for (const t of tokens1) {
984
+ const address = addressOf(t);
985
+ const symbol = symbolOf(t);
986
+ // With an address on both sides only the address counts. If either
987
+ // side omits it (as some responses do for the native asset) a matching
988
+ // symbol is taken as the same token.
989
+ const matched = address
990
+ ? addresses2.has(address) || (symbol && symbolsWithoutAddress2.has(symbol))
991
+ : symbol && symbols2.has(symbol);
992
+ const key = address || symbol;
993
+ if (matched && !seen.has(key)) {
994
+ seen.add(key);
995
+ sharedTokens.push(t.token_symbol || address);
996
+ }
997
+ }
998
+ }
999
+ const totalUsd = (tokens) => tokens === null
1000
+ ? null
1001
+ : tokens.reduce((sum, t) => sum + (t.value_usd ?? t.balance_usd ?? 0), 0);
726
1002
 
727
1003
  return {
728
1004
  addresses: [addr1, addr2], chain,
729
1005
  shared_counterparties: sharedCpAddrs,
730
1006
  shared_tokens: sharedTokens,
731
1007
  balances: [
732
- { address: addr1, total_usd: tokens1.reduce((sum, t) => sum + (t.value_usd ?? t.balance_usd ?? 0), 0) },
733
- { address: addr2, total_usd: tokens2.reduce((sum, t) => sum + (t.value_usd ?? t.balance_usd ?? 0), 0) },
1008
+ { address: addr1, total_usd: totalUsd(tokens1) },
1009
+ { address: addr2, total_usd: totalUsd(tokens2) },
734
1010
  ],
1011
+ ...(errors.length > 0 && { incomplete: true, errors }),
735
1012
  };
736
1013
  }
737
1014
 
@@ -744,9 +1021,9 @@ USAGE: nansen <command> [subcommand] [options]
744
1021
  COMMANDS:
745
1022
  trade DEX swaps/bridges: quote, execute, bridge-status, limit-order
746
1023
  bridge Hyperliquid bridge: quote, execute, status (EVM <-> HL)
747
- perp Hyperliquid perps: order, cancel, close, leverage, positions
748
- research analytics: smart-money, profiler, token, search, perp, portfolio, points
749
- wallet create, list, show, export, default, delete, forget-password
1024
+ perp Hyperliquid perps: order, cancel, close, leverage, transfer, approve-builder-fee, positions, orders, account, meta, screener, leaderboard
1025
+ research analytics: smart-money, profiler, token, search, perp, portfolio
1026
+ wallet ${WALLET_SUBCOMMANDS.join(', ')}
750
1027
  agent Ask the Nansen AI research agent (fast/expert modes)
751
1028
  alerts list, create, update, toggle, delete
752
1029
  web search, fetch
@@ -786,10 +1063,10 @@ EXAMPLES:
786
1063
  nansen research profiler balance --address 0x... --chain ethereum
787
1064
 
788
1065
  DEPRECATED ALIASES (still work, will be removed in a future version):
789
- smart-money, profiler, token, search, perp, portfolio, points → use "nansen research <command>"
1066
+ smart-money, profiler, token, search, portfolio → use "nansen research <command>"
790
1067
  quote, execute → use "nansen trade <command>"
791
1068
 
792
- Research chains: ethereum, solana, base, bnb, arbitrum, polygon, optimism, avalanche, linea, scroll, mantle, ronin, sei, plasma, sonic, monad, hyperevm, iotaevm
1069
+ Research chains: ${SCHEMA.chains.join(', ')}
793
1070
  Trade chains: solana, base
794
1071
  Bridge chains: ethereum, base, arbitrum, polygon, bnb, hyperliquid
795
1072
  Labels: Fund, Smart Trader, 30D/90D/180D Smart Trader, Smart HL Perps Trader
@@ -814,7 +1091,7 @@ SUBCOMMANDS:
814
1091
  USAGE:
815
1092
  nansen trade quote --chain <chain> --from <token> --to <token> --amount <units> [--wallet <name>]
816
1093
  nansen trade quote --chain <chain> --to-chain <chain> --from <token> --to <token> --amount <units>
817
- nansen trade execute --quote <quoteId> [--wallet <name>]
1094
+ nansen trade execute --quote <quoteId> [--wallet <name>] [--dry-run] [--yes]
818
1095
  nansen trade bridge-status --tx-hash <hash> --from-chain <chain> --to-chain <chain>
819
1096
  nansen trade limit-order <create|list|cancel|update> [options]
820
1097
 
@@ -831,6 +1108,13 @@ WALLET:
831
1108
  --wallet <name> Use a named wallet, or "walletconnect" / "wc" for WalletConnect.
832
1109
  Defaults to the default local wallet if omitted.
833
1110
 
1111
+ BEFORE BROADCASTING (execute only):
1112
+ --dry-run Validate and print what would be sent, then stop. Nothing is
1113
+ signed or broadcast and the quote stays usable. Exits 0.
1114
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1). The prompt
1115
+ only appears when stdin is a terminal — agents, CI and pipes run
1116
+ unprompted either way. Declining exits 1 with nothing signed.
1117
+
834
1118
  SYMBOLS:
835
1119
  Common tokens resolve automatically: SOL, ETH, USDC, USDT, WETH
836
1120
  Raw addresses are also accepted.
@@ -893,12 +1177,43 @@ export async function prompt(question, hidden = false, { input = process.stdin,
893
1177
  });
894
1178
  }
895
1179
 
1180
+ // Confirmation prompts belong to the CLI adapter rather than trade/bridge
1181
+ // core. EOF and Ctrl+C resolve as the safe default ("no") so a closed input
1182
+ // cannot leave an irreversible command hanging forever.
1183
+ export async function promptForConfirmation(question, { input = process.stdin, output = process.stderr } = {}) {
1184
+ const rl = readline.createInterface({ input, output });
1185
+ return new Promise((resolve, reject) => {
1186
+ let settled = false;
1187
+ const finish = (answer) => {
1188
+ if (settled) return;
1189
+ settled = true;
1190
+ rl.close();
1191
+ resolve(answer);
1192
+ };
1193
+ const fail = (error) => {
1194
+ if (settled) return;
1195
+ settled = true;
1196
+ rl.close();
1197
+ reject(error);
1198
+ };
1199
+
1200
+ rl.once('close', () => finish(''));
1201
+ rl.once('SIGINT', () => finish(''));
1202
+ rl.once('error', fail);
1203
+ rl.question(question, finish);
1204
+ });
1205
+ }
1206
+
896
1207
  // Build command handlers (returns object with handler functions)
897
1208
  export function buildCommands(deps = {}) {
898
1209
  // Allow dependency injection for testing
899
1210
  const {
900
1211
  api: _api = null,
1212
+ // Password/API-key input belongs to login and may be hidden. Confirmation
1213
+ // is a separate contract: callers must opt into it explicitly so this
1214
+ // prompt can never be reused for an irreversible yes/no decision.
901
1215
  promptFn = prompt,
1216
+ confirmationPromptFn,
902
1217
  log = console.log,
903
1218
  errorOutput: _errorOutput = console.error,
904
1219
  NansenAPIClass: _NansenAPIClass = NansenAPI,
@@ -948,8 +1263,14 @@ export function buildCommands(deps = {}) {
948
1263
  'search': async () => {
949
1264
  // Accept queries as positional args or --query (repeated)
950
1265
  let queries = subArgs.length > 0 ? subArgs : [];
951
- if (options.query) {
1266
+ if (options.query !== undefined) {
952
1267
  const fromOption = Array.isArray(options.query) ? options.query : [options.query];
1268
+ if (!fromOption.every(q => typeof q === 'string')) {
1269
+ throw new NansenError(
1270
+ '--query values must be strings',
1271
+ ErrorCode.INVALID_PARAMS,
1272
+ );
1273
+ }
953
1274
  queries = queries.concat(fromOption);
954
1275
  }
955
1276
  queries = queries.filter(q => q.trim());
@@ -957,14 +1278,9 @@ export function buildCommands(deps = {}) {
957
1278
  throw new NansenError('At least one query is required. Usage: nansen web search "bitcoin price" --num-results 5', ErrorCode.MISSING_PARAM);
958
1279
  }
959
1280
  let numResults;
960
- if (options['num-results'] !== undefined) {
961
- const numResultsRaw = parseInt(options['num-results'], 10);
962
- if (Number.isNaN(numResultsRaw)) {
963
- // Non-numeric — fall back to API default
964
- numResults = undefined;
965
- } else if (numResultsRaw >= 1 && numResultsRaw <= 20) {
966
- numResults = numResultsRaw;
967
- } else {
1281
+ if (options['num-results'] !== undefined || flags['num-results']) {
1282
+ numResults = parseSafeIntegerOption('num-results', options, flags, undefined, 'whole number between 1 and 20');
1283
+ if (numResults < 1 || numResults > 20) {
968
1284
  throw new NansenError('--num-results must be between 1 and 20', ErrorCode.INVALID_PARAMS);
969
1285
  }
970
1286
  }
@@ -974,7 +1290,7 @@ export function buildCommands(deps = {}) {
974
1290
  'fetch': async () => {
975
1291
  // Accept URLs as positional args or --url (repeated)
976
1292
  let urls = subArgs.length > 0 ? subArgs : [];
977
- if (options.url) {
1293
+ if (options.url !== undefined) {
978
1294
  const fromOption = Array.isArray(options.url) ? options.url : [options.url];
979
1295
  urls = urls.concat(fromOption);
980
1296
  }
@@ -986,6 +1302,12 @@ export function buildCommands(deps = {}) {
986
1302
  throw new NansenError(`Invalid URL: "${u}". URLs must include a scheme, e.g. https://example.com`, ErrorCode.INVALID_PARAMS);
987
1303
  }
988
1304
  }
1305
+ if (Array.isArray(options.question)) {
1306
+ throw new NansenError('--question may only be specified once', ErrorCode.INVALID_PARAMS);
1307
+ }
1308
+ if (options.question !== undefined && typeof options.question !== 'string') {
1309
+ throw new NansenError('--question must be a string', ErrorCode.INVALID_PARAMS);
1310
+ }
989
1311
  if (!options.question || !options.question.trim()) {
990
1312
  throw new NansenError('--question is required and cannot be blank. Usage: nansen web fetch https://example.com --question "What is this about?"', ErrorCode.MISSING_PARAM);
991
1313
  }
@@ -1150,8 +1472,10 @@ export function buildCommands(deps = {}) {
1150
1472
  // silently comparing as if it were version 0.0.0, which would show
1151
1473
  // every entry rather than flag the typo.
1152
1474
  if (!/^v?\d+(\.\d+){0,2}$/.test(String(since))) {
1153
- log(`Invalid --since value "${since}": expected a version like 1.43 or 1.43.0.`);
1154
- return;
1475
+ throw new NansenError(
1476
+ `Invalid --since value "${since}": expected a version like 1.43 or 1.43.0.`,
1477
+ ErrorCode.INVALID_PARAMS
1478
+ );
1155
1479
  }
1156
1480
  // Show only entries from the given version onwards
1157
1481
  const lines = content.split('\n');
@@ -1228,10 +1552,13 @@ export function buildCommands(deps = {}) {
1228
1552
  },
1229
1553
 
1230
1554
  'smart-money': async (args, apiInstance, flags, options) => {
1555
+ rejectBlankOption(options.days, 'days', '30');
1556
+ rejectBlankOption(options.chain, 'chain', 'solana');
1557
+ rejectBlankOption(options.chains, 'chains', 'solana');
1231
1558
  const subcommand = args[0] || 'help';
1232
1559
  const chain = options.chain || 'solana';
1233
1560
  const chains = options.chains || [chain];
1234
- const filters = options.filters || {};
1561
+ const filters = parseObjectOption(options.filters, 'filters');
1235
1562
  const orderBy = parseSort(options.sort, options['order-by']);
1236
1563
  const pagination = buildPagination(options);
1237
1564
 
@@ -1242,12 +1569,14 @@ export function buildCommands(deps = {}) {
1242
1569
  : [options.labels];
1243
1570
  }
1244
1571
 
1245
- const days = options.days ? parseInt(options.days) : 30;
1572
+ const days = subcommand === 'historical-holdings'
1573
+ ? parseDaysOption(options, flags)
1574
+ : 30;
1246
1575
 
1247
1576
  const handlers = {
1248
1577
  'netflow': () => apiInstance.smartMoneyNetflow({ chains, filters, orderBy, pagination }),
1249
1578
  'dex-trades': () => apiInstance.smartMoneyDexTrades({ chains, filters, orderBy, pagination }),
1250
- 'perp-trades': () => apiInstance.smartMoneyPerpTrades({ filters, orderBy, pagination, onlyNewPositions: options['only-new-positions'] ?? flags['only-new-positions'] }),
1579
+ 'perp-trades': () => apiInstance.smartMoneyPerpTrades({ filters, orderBy, pagination, onlyNewPositions: resolveBooleanOption(options, flags, 'only-new-positions') }),
1251
1580
  'holdings': () => apiInstance.smartMoneyHoldings({ chains, filters, orderBy, pagination }),
1252
1581
  'dcas': () => apiInstance.smartMoneyDcas({ filters, orderBy, pagination }),
1253
1582
  'historical-holdings': () => apiInstance.smartMoneyHistoricalHoldings({ chains, filters, orderBy, pagination, days }),
@@ -1266,6 +1595,8 @@ export function buildCommands(deps = {}) {
1266
1595
  },
1267
1596
 
1268
1597
  'profiler': async (args, apiInstance, flags, options) => {
1598
+ rejectBlankOption(options.days, 'days', '30');
1599
+ rejectBlankOption(options.chain, 'chain', 'ethereum');
1269
1600
  const subcommand = args[0] || 'help';
1270
1601
  let address = options.address;
1271
1602
  const entityName = options.entity || options['entity-name'];
@@ -1283,20 +1614,33 @@ export function buildCommands(deps = {}) {
1283
1614
  throw new NansenError(err.message, ErrorCode.INVALID_ADDRESS);
1284
1615
  }
1285
1616
  }
1286
- const filters = options.filters || {};
1617
+ const filters = parseObjectOption(options.filters, 'filters');
1287
1618
  const orderBy = parseSort(options.sort, options['order-by']);
1288
1619
  const pagination = buildPagination(options);
1289
- const days = options.days ? parseInt(options.days) : 30;
1620
+ const days = [
1621
+ 'transactions',
1622
+ 'pnl',
1623
+ 'historical-balances',
1624
+ 'counterparties',
1625
+ 'counterparties-batch',
1626
+ 'pnl-summary',
1627
+ 'perp-trades',
1628
+ 'dex-trades',
1629
+ 'trace',
1630
+ 'compare',
1631
+ ].includes(subcommand)
1632
+ ? parseDaysOption(options, flags)
1633
+ : 30;
1290
1634
 
1291
1635
  const handlers = {
1292
1636
  'balance': () => apiInstance.addressBalance({ address, entityName, chain, filters, orderBy }),
1293
1637
  'labels': () => apiInstance.addressLabels({ address, chain, pagination }),
1294
1638
  'transactions': () => {
1295
- const date = parseDateOption(options.date, days);
1639
+ const date = parseDateOption(options.date, days, flags.date);
1296
1640
  return apiInstance.addressTransactions({ address, chain, filters, orderBy, pagination, days, date });
1297
1641
  },
1298
1642
  'pnl': () => {
1299
- const date = parseDateOption(options.date, days);
1643
+ const date = parseDateOption(options.date, days, flags.date);
1300
1644
  return apiInstance.addressPnl({ address, chain, date, days, filters, orderBy, pagination });
1301
1645
  },
1302
1646
  'search': () => apiInstance.entitySearch({ query: options.query }),
@@ -1304,44 +1648,47 @@ export function buildCommands(deps = {}) {
1304
1648
  'related-wallets': () => apiInstance.addressRelatedWallets({ address, chain, orderBy, pagination }),
1305
1649
  'first-funder': () => apiInstance.addressFirstFunder({ address }),
1306
1650
  'counterparties': () => apiInstance.addressCounterparties({ address, chain, filters, orderBy, pagination, days }),
1651
+ 'counterparties-batch': () => {
1652
+ const addresses = options.addresses
1653
+ ? parseAddressList(options.addresses)
1654
+ : (options.file ? readAddressFile(options.file) : []);
1655
+ return apiInstance.addressCounterpartiesBatch({ addresses, chain, filters, orderBy, pagination, days });
1656
+ },
1307
1657
  'pnl-summary': () => apiInstance.addressPnlSummary({ address, chain, orderBy, pagination, days }),
1308
1658
  'perp-positions': () => apiInstance.addressPerpPositions({ address, filters, orderBy, pagination }),
1309
1659
  'perp-trades': () => apiInstance.addressPerpTrades({ address, filters, orderBy, pagination, days }),
1310
1660
  'dex-trades': () => {
1311
- const date = parseDateOption(options.date, days);
1661
+ const date = parseDateOption(options.date, days, flags.date);
1312
1662
  return apiInstance.addressDexTrades({ address, chain, filters, orderBy, pagination, days, date });
1313
1663
  },
1314
1664
  'batch': () => {
1665
+ rejectBlankOption(options.delay, 'delay', '1000');
1315
1666
  let addresses = [];
1316
1667
  if (options.addresses) {
1317
1668
  addresses = parseAddressList(options.addresses);
1318
1669
  } else if (options.file) {
1319
- const content = fs.readFileSync(options.file, 'utf8');
1320
- try {
1321
- const parsed = JSON.parse(content);
1322
- if (!Array.isArray(parsed)) {
1323
- throw new NansenError('File must contain a JSON array of address strings or one address per line', ErrorCode.INVALID_PARAMS);
1324
- }
1325
- if (!parsed.every(item => typeof item === 'string')) {
1326
- throw new NansenError('File must contain a JSON array of address strings or one address per line', ErrorCode.INVALID_PARAMS);
1327
- }
1328
- addresses = parsed.map(a => a.trim()).filter(Boolean);
1329
- } catch (e) {
1330
- if (e instanceof NansenError) throw e;
1331
- addresses = content.split('\n').map(a => a.trim()).filter(Boolean);
1332
- }
1670
+ addresses = readAddressFile(options.file);
1333
1671
  }
1334
1672
  if (addresses.length > 100) {
1335
1673
  throw new NansenError('Batch is limited to 100 addresses', ErrorCode.INVALID_PARAMS);
1336
1674
  }
1337
- const include = options.include ? options.include.split(',').map(s => s.trim()) : ['labels', 'balance'];
1338
- const delayMs = options.delay ? parseInt(options.delay) : 1000;
1675
+ const parsedInclude = parseCsvOption(options.include, 'include');
1676
+ const include = (parsedInclude && parsedInclude.length > 0) ? parsedInclude : ['labels', 'balance'];
1677
+ const delayMs = parseNonNegativeSafeIntegerOption('delay', options, flags, 1000);
1339
1678
  return batchProfile(apiInstance, { addresses, chain, include, delayMs });
1340
1679
  },
1341
1680
  'trace': () => {
1342
- const depth = options.depth ? Math.max(1, Math.min(parseInt(options.depth), 5)) : 2;
1343
- const width = options.width ? parseInt(options.width) : 10;
1344
- const delayMs = options.delay ? parseInt(options.delay) : 1000;
1681
+ rejectBlankOption(options.delay, 'delay', '1000');
1682
+ rejectBlankOption(options.depth, 'depth', '2');
1683
+ if (flags.depth) {
1684
+ throw new NansenError(
1685
+ '--depth requires a safe integer value',
1686
+ ErrorCode.INVALID_PARAMS,
1687
+ );
1688
+ }
1689
+ const depth = options.depth ?? 2;
1690
+ const width = parseNonNegativeSafeIntegerOption('width', options, flags, 10);
1691
+ const delayMs = parseNonNegativeSafeIntegerOption('delay', options, flags, 1000);
1345
1692
  return traceCounterparties(apiInstance, { address, chain, depth, width, days, delayMs });
1346
1693
  },
1347
1694
  'compare': () => {
@@ -1349,7 +1696,7 @@ export function buildCommands(deps = {}) {
1349
1696
  return compareWallets(apiInstance, { addresses: addrs, chain, days });
1350
1697
  },
1351
1698
  'help': () => ({
1352
- commands: ['balance', 'labels', 'transactions', 'pnl', 'search', 'historical-balances', 'related-wallets', 'first-funder', 'counterparties', 'pnl-summary', 'perp-positions', 'perp-trades', 'dex-trades', 'batch', 'trace', 'compare'],
1699
+ commands: ['balance', 'labels', 'transactions', 'pnl', 'search', 'historical-balances', 'related-wallets', 'first-funder', 'counterparties', 'counterparties-batch', 'pnl-summary', 'perp-positions', 'perp-trades', 'dex-trades', 'batch', 'trace', 'compare'],
1353
1700
  description: 'Wallet profiling endpoints',
1354
1701
  example: 'nansen research profiler compare --addresses "0xABC...,0xDEF..." --chain ethereum'
1355
1702
  })
@@ -1368,25 +1715,40 @@ export function buildCommands(deps = {}) {
1368
1715
  },
1369
1716
 
1370
1717
  'token': async (args, apiInstance, flags, options) => {
1718
+ rejectBlankOption(options.days, 'days', '30');
1719
+ rejectBlankOption(options.chain, 'chain', 'solana');
1720
+ rejectBlankOption(options.chains, 'chains', 'solana');
1721
+ rejectBlankOption(options.timeframe, 'timeframe', '1d');
1722
+ rejectBlankOption(options['buy-or-sell'], 'buy-or-sell', 'SELL');
1371
1723
  const subcommand = args[0] || 'help';
1372
1724
  const chain = options.chain || 'solana';
1373
1725
  const tokenAddress = normalizeAddress(options.token || options['token-address'], chain);
1374
1726
  const tokenSymbol = options.symbol || options['token-symbol'];
1375
1727
  const chains = options.chains || [chain];
1376
1728
  const timeframe = options.timeframe || '24h';
1377
- const filters = options.filters || {};
1729
+ const filters = parseObjectOption(options.filters, 'filters');
1378
1730
  const orderBy = parseSort(options.sort, options['order-by']);
1379
1731
  const pagination = buildPagination(options);
1380
- const days = options.days ? parseInt(options.days) : 30;
1732
+ const days = [
1733
+ 'flows',
1734
+ 'dex-trades',
1735
+ 'pnl',
1736
+ 'who-bought-sold',
1737
+ 'transfers',
1738
+ 'perp-trades',
1739
+ 'perp-pnl-leaderboard',
1740
+ ].includes(subcommand)
1741
+ ? parseDaysOption(options, flags)
1742
+ : 30;
1381
1743
 
1382
1744
  // Convenience filter for smart money only
1383
- const onlySmartMoney = options['smart-money'] || flags['smart-money'] || false;
1745
+ const onlySmartMoney = resolveBooleanOption(options, flags, 'smart-money') ?? false;
1384
1746
  if (onlySmartMoney) {
1385
1747
  filters.include_smart_money_labels = filters.include_smart_money_labels ||
1386
1748
  ['Fund', 'Smart Trader', '30D Smart Trader', '90D Smart Trader', '180D Smart Trader'];
1387
1749
  }
1388
1750
 
1389
- const includeStablecoins = options['include-stablecoins'] ?? flags['include-stablecoins'];
1751
+ const includeStablecoins = resolveBooleanOption(options, flags, 'include-stablecoins');
1390
1752
  if (includeStablecoins !== undefined) {
1391
1753
  filters.include_stablecoins = includeStablecoins;
1392
1754
  }
@@ -1397,19 +1759,26 @@ export function buildCommands(deps = {}) {
1397
1759
  'info': () => apiInstance.tokenInformation({ tokenAddress, chain, timeframe: options.timeframe }),
1398
1760
  'screener': async () => {
1399
1761
  const search = options.search;
1400
- // When searching, fetch more results to filter from (API has no server-side search)
1401
- const searchPagination = search
1402
- ? { page: 1, per_page: Math.max(500, pagination?.per_page || 0) }
1762
+ if (search !== undefined && typeof search !== 'string') {
1763
+ throw new NansenError('--search must be a string', ErrorCode.INVALID_PARAMS);
1764
+ }
1765
+ // When searching, fetch more results to filter from (API has no server-side search).
1766
+ // --page/--limit are applied client-side to the filtered list, so the
1767
+ // candidate fetch has to cover every page up to the requested one.
1768
+ const requestedLimit = pagination?.per_page || 100;
1769
+ const requestedPage = pagination?.page || 1;
1770
+ const searchPagination = search
1771
+ ? { page: 1, per_page: Math.max(500, requestedPage * requestedLimit) }
1403
1772
  : pagination;
1404
1773
  const result = await apiInstance.tokenScreener({ chains, timeframe, filters, orderBy, pagination: searchPagination });
1405
1774
  if (search) {
1406
1775
  const q = search.toLowerCase();
1407
- const requestedLimit = pagination?.per_page || 100;
1776
+ const offset = (requestedPage - 1) * requestedLimit;
1408
1777
  const filterArr = (arr) => arr.filter(t =>
1409
1778
  (t.token_symbol && t.token_symbol.toLowerCase().includes(q)) ||
1410
1779
  (t.token_name && t.token_name.toLowerCase().includes(q)) ||
1411
1780
  (t.token_address && t.token_address.toLowerCase() === q)
1412
- ).slice(0, requestedLimit);
1781
+ ).slice(offset, offset + requestedLimit);
1413
1782
  // Handle nested response shapes: {data: [...]} or {data: {data: [...]}}
1414
1783
  if (Array.isArray(result?.data)) {
1415
1784
  return { ...result, data: filterArr(result.data) };
@@ -1421,7 +1790,7 @@ export function buildCommands(deps = {}) {
1421
1790
  },
1422
1791
  'holders': () => apiInstance.tokenHolders({ tokenAddress, chain, labelType: onlySmartMoney ? 'smart_money' : 'all_holders', filters, orderBy, pagination, withLabels: resolveBooleanOption(options, flags, 'premium-labels') }),
1423
1792
  'flows': () => {
1424
- const date = parseDateOption(options.date, days);
1793
+ const date = parseDateOption(options.date, days, flags.date);
1425
1794
  const label = options.label;
1426
1795
  return apiInstance.tokenFlows({ tokenAddress, chain, label, filters, orderBy, pagination, days, date });
1427
1796
  },
@@ -1431,8 +1800,15 @@ export function buildCommands(deps = {}) {
1431
1800
  return apiInstance.tokenPnlLeaderboard({ tokenAddress, chain, filters, orderBy, pagination, days, withLabels });
1432
1801
  },
1433
1802
  'who-bought-sold': () => {
1434
- const date = parseDateOption(options.date, days);
1435
- const buyOrSell = (options['buy-or-sell'] || 'BUY').toUpperCase();
1803
+ const date = parseDateOption(options.date, days, flags.date);
1804
+ const buyOrSellRaw = options['buy-or-sell'];
1805
+ if (buyOrSellRaw !== undefined && typeof buyOrSellRaw !== 'string') {
1806
+ throw new NansenError('--buy-or-sell must be BUY or SELL', ErrorCode.INVALID_PARAMS);
1807
+ }
1808
+ const buyOrSell = (buyOrSellRaw || 'BUY').toUpperCase();
1809
+ if (buyOrSell !== 'BUY' && buyOrSell !== 'SELL') {
1810
+ throw new NansenError('--buy-or-sell must be BUY or SELL', ErrorCode.INVALID_PARAMS);
1811
+ }
1436
1812
  return apiInstance.tokenWhoBoughtSold({ tokenAddress, chain, buyOrSell, filters, orderBy, pagination, days, date });
1437
1813
  },
1438
1814
  'flow-intelligence': () => apiInstance.tokenFlowIntelligence({ tokenAddress, chain, timeframe: options.timeframe || '1d' }),
@@ -1451,7 +1827,7 @@ export function buildCommands(deps = {}) {
1451
1827
  },
1452
1828
  'top-tokens': () => {
1453
1829
  const marketCapGroup = options['market-cap'] || options['market-cap-group'];
1454
- const limit = options.limit ? parseInt(options.limit) : undefined;
1830
+ const limit = parseNonNegativeSafeIntegerOption('limit', options, flags);
1455
1831
  return apiInstance.topTokens({ marketCapGroup, limit });
1456
1832
  },
1457
1833
  'help': () => ({
@@ -1519,24 +1895,21 @@ export function buildCommands(deps = {}) {
1519
1895
  },
1520
1896
 
1521
1897
  'perp': async (args, apiInstance, flags, options) => {
1898
+ rejectBlankOption(options.days, 'days', '30');
1522
1899
  const subcommand = args[0] || 'help';
1523
- const filters = options.filters || {};
1900
+ const filters = parseObjectOption(options.filters, 'filters');
1524
1901
  const orderBy = parseSort(options.sort, options['order-by']);
1525
1902
  const pagination = buildPagination(options);
1526
- const days = options.days ? parseInt(options.days) : 30;
1903
+ const days = ['screener', 'leaderboard'].includes(subcommand)
1904
+ ? parseDaysOption(options, flags)
1905
+ : 30;
1527
1906
 
1528
1907
  const handlers = {
1529
1908
  'screener': () => {
1530
1909
  const traderType = options['trader-type'];
1531
- const sectorsFilter = options['sectors-filter']
1532
- ? options['sectors-filter'].split(',').map(s => s.trim()).filter(Boolean)
1533
- : undefined;
1534
- const smLabelFilter = options['sm-label-filter']
1535
- ? options['sm-label-filter'].split(',').map(s => s.trim()).filter(Boolean)
1536
- : undefined;
1537
- const traderLabelFilter = options['trader-label-filter']
1538
- ? options['trader-label-filter'].split(',').map(s => s.trim()).filter(Boolean)
1539
- : undefined;
1910
+ const sectorsFilter = parseCsvOption(options['sectors-filter'], 'sectors-filter');
1911
+ const smLabelFilter = parseCsvOption(options['sm-label-filter'], 'sm-label-filter');
1912
+ const traderLabelFilter = parseCsvOption(options['trader-label-filter'], 'trader-label-filter');
1540
1913
  return apiInstance.perpScreener({ filters, orderBy, pagination, days, traderType, sectorsFilter, smLabelFilter, traderLabelFilter });
1541
1914
  },
1542
1915
  'leaderboard': () => {
@@ -1558,6 +1931,7 @@ export function buildCommands(deps = {}) {
1558
1931
  },
1559
1932
 
1560
1933
  'search': async (args, apiInstance, flags, options) => {
1934
+ rejectBlankOption(options.chain, 'chain', 'solana');
1561
1935
  return apiInstance.generalSearch({
1562
1936
  query: args[0] || options.query,
1563
1937
  resultType: options.type,
@@ -1566,25 +1940,8 @@ export function buildCommands(deps = {}) {
1566
1940
  });
1567
1941
  },
1568
1942
 
1569
- 'points': async (args, apiInstance, flags, options) => {
1570
- const subcommand = args[0] || 'help';
1571
- const tier = options.tier;
1572
- const pagination = buildPagination(options);
1573
-
1574
- const handlers = {
1575
- 'leaderboard': () => apiInstance.pointsLeaderboard({ tier, pagination }),
1576
- 'help': () => ({
1577
- commands: ['leaderboard'],
1578
- description: 'Nansen Points analytics endpoints',
1579
- example: 'nansen points leaderboard --limit 100'
1580
- })
1581
- };
1582
-
1583
- if (!handlers[subcommand]) {
1584
- return { error: `Unknown subcommand: ${subcommand}`, available: Object.keys(handlers) };
1585
- }
1586
-
1587
- return handlers[subcommand]();
1943
+ 'points': async () => {
1944
+ throw new CommandError('The points leaderboard endpoint has been removed. Run "nansen research" to explore other analytics commands.', 'COMMAND_UNAVAILABLE');
1588
1945
  },
1589
1946
 
1590
1947
  'prediction-market': async (args, apiInstance, flags, options) => {
@@ -1601,20 +1958,21 @@ export function buildCommands(deps = {}) {
1601
1958
  const pagination = buildPagination(options);
1602
1959
 
1603
1960
  // Screener-specific filter options
1604
- const tags = options.tags ? options.tags.split(',').map(t => t.trim()) : undefined;
1605
- const minLiquidity = options['min-liquidity'] != null ? Number(options['min-liquidity']) : undefined;
1606
- const maxLiquidity = options['max-liquidity'] != null ? Number(options['max-liquidity']) : undefined;
1607
- const minUniqueTraders24h = options['min-unique-traders-24h'] != null ? Number(options['min-unique-traders-24h']) : undefined;
1608
- const maxUniqueTraders24h = options['max-unique-traders-24h'] != null ? Number(options['max-unique-traders-24h']) : undefined;
1609
- const minVolume24hr = options['min-volume-24hr'] != null ? Number(options['min-volume-24hr']) : undefined;
1610
- const maxVolume24hr = options['max-volume-24hr'] != null ? Number(options['max-volume-24hr']) : undefined;
1961
+ const isScreener = subcommand === 'market-screener' || subcommand === 'event-screener';
1962
+ const tags = parseCsvOption(options.tags, 'tags');
1963
+ const minLiquidity = isScreener ? parseFiniteNumberOption('min-liquidity', options, flags) : undefined;
1964
+ const maxLiquidity = isScreener ? parseFiniteNumberOption('max-liquidity', options, flags) : undefined;
1965
+ const minUniqueTraders24h = isScreener ? parseFiniteNumberOption('min-unique-traders-24h', options, flags) : undefined;
1966
+ const maxUniqueTraders24h = isScreener ? parseFiniteNumberOption('max-unique-traders-24h', options, flags) : undefined;
1967
+ const minVolume24hr = isScreener ? parseFiniteNumberOption('min-volume-24hr', options, flags) : undefined;
1968
+ const maxVolume24hr = isScreener ? parseFiniteNumberOption('max-volume-24hr', options, flags) : undefined;
1611
1969
  const negRisk = resolveBooleanOption(options, flags, 'neg-risk');
1612
- const minOpenInterest = options['min-open-interest'] != null ? Number(options['min-open-interest']) : undefined;
1613
- const maxOpenInterest = options['max-open-interest'] != null ? Number(options['max-open-interest']) : undefined;
1970
+ const minOpenInterest = isScreener ? parseFiniteNumberOption('min-open-interest', options, flags) : undefined;
1971
+ const maxOpenInterest = isScreener ? parseFiniteNumberOption('max-open-interest', options, flags) : undefined;
1614
1972
  const endDateBefore = options['end-date-before'];
1615
1973
  const endDateAfter = options['end-date-after'];
1616
- const minPrice = options['min-price'] != null ? Number(options['min-price']) : undefined;
1617
- const maxPrice = options['max-price'] != null ? Number(options['max-price']) : undefined;
1974
+ const minPrice = subcommand === 'market-screener' ? parseFiniteNumberOption('min-price', options, flags) : undefined;
1975
+ const maxPrice = subcommand === 'market-screener' ? parseFiniteNumberOption('max-price', options, flags) : undefined;
1618
1976
 
1619
1977
  const handlers = {
1620
1978
  'ohlcv': () => apiInstance.pmOhlcv({ marketId, orderBy, pagination }),
@@ -1684,7 +2042,8 @@ export function buildCommands(deps = {}) {
1684
2042
  };
1685
2043
 
1686
2044
  // 'trade' delegates to quote/execute from buildTradingCommands and limit-order from buildLimitOrderCommands
1687
- const tradingCmds = buildTradingCommands(deps);
2045
+ const executionDeps = { ...deps, promptFn: confirmationPromptFn };
2046
+ const tradingCmds = buildTradingCommands(executionDeps);
1688
2047
  const limitOrderCmds = buildLimitOrderCommands(deps);
1689
2048
  cmds['trade'] = async (args, apiInstance, flags, options) => {
1690
2049
  const sub = args[0];
@@ -1722,7 +2081,7 @@ USAGE:
1722
2081
  };
1723
2082
 
1724
2083
  // 'bridge' delegates to quote/execute/status from buildBridgeCommands
1725
- const bridgeCmds = buildBridgeCommands(deps);
2084
+ const bridgeCmds = buildBridgeCommands(executionDeps);
1726
2085
  cmds['bridge'] = async (args, apiInstance, flags, options) => {
1727
2086
  const sub = args[0];
1728
2087
  if (!sub || sub === 'help') {
@@ -1735,9 +2094,14 @@ SUBCOMMANDS:
1735
2094
 
1736
2095
  USAGE:
1737
2096
  nansen bridge quote --from-chain base --to-chain hyperliquid --from-token USDC --amount 1000000
1738
- nansen bridge execute --quote <quoteId>
2097
+ nansen bridge execute --quote <quoteId> [--dry-run] [--yes]
1739
2098
  nansen bridge status --request-id <id>
1740
2099
 
2100
+ BEFORE BROADCASTING (execute only):
2101
+ --dry-run Validate and print what would be signed, then stop. Exits 0.
2102
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1). The prompt only
2103
+ appears when stdin is a terminal; declining exits 1, signing nothing.
2104
+
1741
2105
  SUPPORTED ROUTES:
1742
2106
  ${formatBridgeRoutes()}`);
1743
2107
  return;
@@ -1797,7 +2161,7 @@ USAGE:
1797
2161
  }
1798
2162
 
1799
2163
  // Categories that moved under 'research'
1800
- export const DEPRECATED_TO_RESEARCH = new Set(['smart-money', 'profiler', 'token', 'search', 'portfolio', 'points']);
2164
+ export const DEPRECATED_TO_RESEARCH = new Set(['smart-money', 'profiler', 'token', 'search', 'portfolio']);
1801
2165
  // Subcommands that moved under 'trade'
1802
2166
  export const DEPRECATED_TO_TRADE = new Set(['quote', 'execute']);
1803
2167
 
@@ -1821,7 +2185,16 @@ export const RESEARCH_CATEGORY_ALIASES = {
1821
2185
 
1822
2186
  // Generate help text for a specific subcommand using SCHEMA
1823
2187
  export function generateSubcommandHelp(command, subcommand, prefix = null) {
1824
- const cmdSchema = SCHEMA.commands[command] || SCHEMA.commands.research.subcommands[command];
2188
+ // `perp` is both a top-level trading command and a research category, and
2189
+ // the two have different subcommands. Look in both places and use whichever
2190
+ // actually holds this subcommand (top-level wins when both do) instead of
2191
+ // stopping at the first schema whose *name* matches — that made
2192
+ // `research perp screener --help` fall back to listing the category's
2193
+ // subcommands, i.e. telling the caller to run the command they just ran.
2194
+ const topSchema = SCHEMA.commands[command];
2195
+ const researchSchema = SCHEMA.commands.research.subcommands[command];
2196
+ const fromResearch = !topSchema?.subcommands?.[subcommand] && Boolean(researchSchema?.subcommands?.[subcommand]);
2197
+ const cmdSchema = fromResearch ? researchSchema : topSchema || researchSchema;
1825
2198
  if (!cmdSchema) return null;
1826
2199
 
1827
2200
  const subSchema = cmdSchema.subcommands?.[subcommand];
@@ -1852,7 +2225,7 @@ export function generateSubcommandHelp(command, subcommand, prefix = null) {
1852
2225
 
1853
2226
  const exampleValues = { address: '0x...', token: '0x...', query: '"term"', symbol: 'BTC', date: '2024-01-01' };
1854
2227
  const chain = subSchema.options?.chain?.default || 'solana';
1855
- const cmdPrefix = prefix || (DEPRECATED_TO_RESEARCH.has(command) ? `research ${command}` : command);
2228
+ const cmdPrefix = prefix || (fromResearch || DEPRECATED_TO_RESEARCH.has(command) ? `research ${command}` : command);
1856
2229
  let example = subSchema.examples?.[0] || `nansen ${cmdPrefix} ${subcommand}`;
1857
2230
  if (!subSchema.examples?.length && subSchema.options) {
1858
2231
  for (const [name, opt] of Object.entries(subSchema.options)) {
@@ -1875,12 +2248,45 @@ export async function runCLI(rawArgs, deps = {}) {
1875
2248
  exit = process.exit,
1876
2249
  NansenAPIClass = NansenAPI,
1877
2250
  commandOverrides = {},
1878
- // Injectable so tests can exercise both renderings; defaults to the real
1879
- // terminal, which is false under a pipe or in CI.
2251
+ // Output TTY controls human-vs-structured error rendering. Keep the
2252
+ // existing `isTTY` seam for callers/tests that inject both terminal states.
1880
2253
  isTTY = process.stdout.isTTY,
1881
2254
  } = deps;
1882
2255
 
1883
- const { _: positional, flags, options } = parseArgs(rawArgs);
2256
+ // Command-layer interactivity is intentionally governed by stdin. Besides
2257
+ // trade/bridge confirmation, buildCommands' existing `login --human` prompt
2258
+ // consumes this same signal; stdout may be redirected while a person still
2259
+ // answers either prompt on stdin. The separate `isTTY` destructured above
2260
+ // remains the stdout signal for human-vs-structured error rendering. Callers
2261
+ // can split the signals with `isInputTTY`; legacy `isTTY` injection still
2262
+ // drives both for compatibility.
2263
+ const isInputTTY = deps.isInputTTY ?? (deps.isTTY ?? process.stdin.isTTY);
2264
+
2265
+ // Pass the CLI-owned terminal seams into command modules. Keeping these out
2266
+ // of core means direct/library callers are non-interactive unless they
2267
+ // explicitly provide a prompt.
2268
+ const inputInteractiveDeps = {
2269
+ ...deps,
2270
+ isTTY: isInputTTY,
2271
+ promptFn: deps.promptFn ?? prompt,
2272
+ confirmationPromptFn: deps.confirmationPromptFn ?? promptForConfirmation,
2273
+ confirmationLog: deps.confirmationLog ?? errorOutput,
2274
+ };
2275
+ const topLevelTradingDeps = {
2276
+ ...inputInteractiveDeps,
2277
+ promptFn: inputInteractiveDeps.confirmationPromptFn,
2278
+ };
2279
+
2280
+ let parsed;
2281
+ try {
2282
+ parsed = parseArgs(rawArgs);
2283
+ } catch (error) {
2284
+ const errorData = formatError(error);
2285
+ output(formatOutput(errorData).text);
2286
+ exit(1);
2287
+ return { type: 'error', data: errorData };
2288
+ }
2289
+ const { _: positional, flags, options } = parsed;
1884
2290
 
1885
2291
  // Resolve command aliases
1886
2292
  const rawCommand = positional[0] || 'help';
@@ -1923,7 +2329,11 @@ export async function runCLI(rawArgs, deps = {}) {
1923
2329
 
1924
2330
  // mcp prints its own output via `log`; runCLI callers inject their stdout
1925
2331
  // sink as `output`, so map it across (an explicit `log` dep still wins).
1926
- const commands = { ...buildCommands(deps), ...buildWalletCommands(deps), ...buildTradingCommands(deps), ...buildAlertsCommands(deps), ...buildAgentCommands(deps), ...buildMcpCommands({ ...deps, log: deps.log ?? output }), ...buildCompletionCommands({ ...deps, log: deps.log ?? output }), ...commandOverrides };
2332
+ // Only execute/login handlers consume the stdin-interactivity seam. Other
2333
+ // modules retain their existing deps: notably wallet export interprets
2334
+ // `isTTY` as stdout visibility when deciding whether to warn about printing
2335
+ // private keys, so substituting the stdin signal there changes its semantics.
2336
+ const commands = { ...buildCommands(inputInteractiveDeps), ...buildWalletCommands(deps), ...buildTradingCommands(topLevelTradingDeps), ...buildAlertsCommands(deps), ...buildAgentCommands(deps), ...buildMcpCommands({ ...deps, log: deps.log ?? output }), ...buildCompletionCommands({ ...deps, log: deps.log ?? output }), ...commandOverrides };
1927
2337
 
1928
2338
  if (flags.version || flags.v) {
1929
2339
  output(VERSION);