nansen-cli 1.45.0 → 2.0.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.
Files changed (85) hide show
  1. package/CHANGELOG.md +172 -0
  2. package/README.md +158 -18
  3. package/docs/browser-login.md +117 -0
  4. package/package.json +11 -2
  5. package/scripts/postinstall.js +35 -30
  6. package/skills/nansen-agent-guide/SKILL.md +13 -2
  7. package/skills/nansen-alerts-webhook-listener/SKILL.md +5 -2
  8. package/skills/nansen-dca-tracker/SKILL.md +10 -2
  9. package/skills/nansen-defi-positions/SKILL.md +5 -2
  10. package/skills/nansen-exit-signals/SKILL.md +10 -2
  11. package/skills/nansen-fund-tracker/SKILL.md +10 -2
  12. package/skills/nansen-general-search/SKILL.md +10 -2
  13. package/skills/nansen-holder-analysis/SKILL.md +10 -2
  14. package/skills/nansen-limit-orders/SKILL.md +6 -3
  15. package/skills/nansen-perp-screener/SKILL.md +10 -2
  16. package/skills/nansen-perp-trader-profile/SKILL.md +10 -2
  17. package/skills/nansen-polymarket-deep-dive/SKILL.md +10 -2
  18. package/skills/nansen-polymarket-insider-scan/SKILL.md +10 -2
  19. package/skills/nansen-polymarket-trader-profile/SKILL.md +10 -2
  20. package/skills/nansen-portfolio-tracker/SKILL.md +10 -2
  21. package/skills/nansen-prediction-markets/SKILL.md +10 -2
  22. package/skills/nansen-sm-cross-chain-flows/SKILL.md +10 -2
  23. package/skills/nansen-smart-alerts/SKILL.md +9 -4
  24. package/skills/nansen-smart-money-alpha/SKILL.md +10 -2
  25. package/skills/nansen-smart-money-tracker/SKILL.md +10 -2
  26. package/skills/nansen-smart-money-trend/SKILL.md +10 -2
  27. package/skills/nansen-token-research/SKILL.md +10 -2
  28. package/skills/nansen-token-screener/SKILL.md +14 -4
  29. package/skills/nansen-token-transfer-analysis/SKILL.md +10 -2
  30. package/skills/nansen-trading/SKILL.md +27 -2
  31. package/skills/nansen-wallet-batch/SKILL.md +10 -2
  32. package/skills/nansen-wallet-clustering/SKILL.md +10 -2
  33. package/skills/nansen-wallet-deep-dive/SKILL.md +10 -2
  34. package/skills/nansen-wallet-keychain-migration/SKILL.md +23 -15
  35. package/skills/nansen-wallet-manager/SKILL.md +26 -10
  36. package/skills/nansen-wallet-profiler/SKILL.md +10 -2
  37. package/skills/nansen-web-fetcher/SKILL.md +5 -2
  38. package/skills/nansen-web-searcher/SKILL.md +5 -2
  39. package/src/api.js +319 -129
  40. package/src/auth-browser.js +16 -0
  41. package/src/auth-credentials.js +73 -0
  42. package/src/auth-device.js +242 -0
  43. package/src/auth-key-input.js +46 -0
  44. package/src/auth-login.js +90 -0
  45. package/src/auth-state.js +487 -0
  46. package/src/auth-store-native.js +20 -0
  47. package/src/auth-store-worker.js +64 -0
  48. package/src/auth-store.js +140 -0
  49. package/src/auto-paginate.js +272 -0
  50. package/src/bridge.js +309 -85
  51. package/src/cache-inspect.js +345 -0
  52. package/src/chain-ids.js +1 -2
  53. package/src/cli.js +779 -286
  54. package/src/commands/agent.js +20 -9
  55. package/src/commands/alerts.js +1 -1
  56. package/src/commands/completion.js +2 -15
  57. package/src/commands/mcp.js +22 -20
  58. package/src/commands/research.js +4 -2
  59. package/src/cost-cache.js +16 -2
  60. package/src/debug.js +348 -0
  61. package/src/doctor.js +22 -45
  62. package/src/ens.js +3 -1
  63. package/src/execute-guard.js +116 -0
  64. package/src/hl-action.js +41 -13
  65. package/src/limit-order.js +9 -1
  66. package/src/mcp-client-config.js +169 -0
  67. package/src/mcp-client-config.json +17 -0
  68. package/src/mcp-verify.js +6 -5
  69. package/src/perp.js +61 -9
  70. package/src/privy.js +12 -12
  71. package/src/query-options.js +38 -6
  72. package/src/response-meta.js +57 -2
  73. package/src/rpc-urls.js +9 -11
  74. package/src/schema.json +309 -30
  75. package/src/semver.js +23 -4
  76. package/src/swap-simulation.js +35 -30
  77. package/src/telemetry.js +20 -0
  78. package/src/trading.js +806 -40
  79. package/src/transfer.js +75 -9
  80. package/src/update-check.js +9 -1
  81. package/src/wallet.js +240 -20
  82. package/src/walletconnect-trading.js +29 -8
  83. package/src/walletconnect-x402.js +9 -5
  84. package/src/x402-svm.js +123 -64
  85. package/src/x402.js +46 -14
package/src/cli.js CHANGED
@@ -1,10 +1,13 @@
1
+ import { authConfigView } from './auth-credentials.js';
2
+ import { browserLogin, defaultAuthState, cleanupMessage } from './auth-login.js';
3
+ import { readApiKeyInput } from './auth-key-input.js';
1
4
  /**
2
5
  * Nansen CLI - Core logic (testable)
3
6
  * Extracted from index.js for coverage
4
7
  */
5
8
 
6
- import { NansenAPI, NansenError, CommandError, ErrorCode, saveConfig, deleteConfig, getConfigFile, clearCache, getCacheDir, validateAddress, normalizeAddress, sleep } from './api.js';
7
- import { buildWalletCommands } from './wallet.js';
9
+ import { NansenAPI, NansenError, CommandError, ErrorCode, getConfigFile, validateAddress, normalizeAddress, sleep } from './api.js';
10
+ import { buildWalletCommands, WALLET_SUBCOMMANDS } from './wallet.js';
8
11
  import { buildBridgeCommands, formatBridgeRoutes } from './bridge.js';
9
12
  import { buildPerpCommands } from './perp.js';
10
13
  import { buildTradingCommands } from './trading.js';
@@ -14,7 +17,8 @@ import { buildAgentCommands } from './commands/agent.js';
14
17
  import { buildMcpCommands } from './commands/mcp.js';
15
18
  import { buildCompletionCommands } from './commands/completion.js';
16
19
  import { buildResearchCommands, RESEARCH_HISTORICAL_SUBCOMMANDS, RESEARCH_SUBCOMMANDS } from './commands/research.js';
17
- import { buildPagination, parseSort, parseCsvOption, rejectBlankOption } from './query-options.js';
20
+ import { buildPagination, parseSort, parseCsvOption, rejectBlankOption, parseObjectOption } from './query-options.js';
21
+ import { enableAutoPagination, DEFAULT_MAX_PAGES, MAX_PAGES_LIMIT, locateRows } from './auto-paginate.js';
18
22
  export { buildPagination, parseSort };
19
23
  import { resolveAddress, isEnsName } from './ens.js';
20
24
  import { compareSemver } from './semver.js';
@@ -22,8 +26,10 @@ import fs from 'fs';
22
26
  import { getUpdateNotification, getUpgradeNotice, scheduleUpdateCheck } from './update-check.js';
23
27
  import { getAuthStatus, runDoctorChecks, runConnectivityChecks, formatDoctorReport } from './doctor.js';
24
28
  import { refreshCostMapIfStale, getCostForEndpoint, creditsCharged } from './cost-cache.js';
29
+ import { collectCacheStats, clearCaches, formatCacheStats, formatCacheClear } from './cache-inspect.js';
25
30
  import { creditWarning, noticeWarnings } from './response-meta.js';
26
- import { trackCommandSucceeded, trackCommandFailed } from './telemetry.js';
31
+ import { trackCommandSucceeded, trackCommandFailed, trackAuthCommand } from './telemetry.js';
32
+ import { setDebugEnabled } from './debug.js';
27
33
  import { createRequire } from 'module';
28
34
  import * as readline from 'readline';
29
35
 
@@ -49,36 +55,53 @@ export const SCHEMA = { version: VERSION, ...schemaDefinition };
49
55
  * Returns true/false/undefined (undefined = not supplied).
50
56
  */
51
57
  export function resolveBooleanOption(options, flags, key) {
52
- if (options[key] !== undefined) {
53
- const val = String(options[key]).toLowerCase();
58
+ const optionValue = options[key];
59
+ const flagValue = flags[key];
60
+
61
+ if (Array.isArray(optionValue) || Array.isArray(flagValue) ||
62
+ (optionValue !== undefined && flagValue !== undefined)) {
63
+ throw new NansenError(`--${key} cannot be repeated`, ErrorCode.INVALID_PARAMS);
64
+ }
65
+ if (optionValue !== undefined) {
66
+ const val = String(optionValue).toLowerCase();
54
67
  if (val === 'true' || val === '1') return true;
55
68
  if (val === 'false' || val === '0') return false;
69
+ throw new NansenError(`--${key} must be true or false`, ErrorCode.INVALID_PARAMS);
56
70
  }
57
- if (flags[key] !== undefined) return Boolean(flags[key]);
71
+ if (flagValue !== undefined) return Boolean(flagValue);
58
72
  return undefined;
59
73
  }
60
74
 
61
75
  // ============= Field Filtering =============
62
76
 
63
77
  /**
64
- * Filter object to include only specified fields
65
- * Supports nested paths with dot notation (e.g., "data.results")
78
+ * Filter object to include only specified fields.
79
+ *
80
+ * A bare name ("address") matches that key at any depth. A dotted path
81
+ * ("data.results", "results.address") matches only at that position, counted
82
+ * from the root of the payload; array elements do not add a segment, so
83
+ * "results.address" selects `address` inside each item of `results`.
66
84
  */
67
85
  export function filterFields(data, fields) {
68
86
  if (!fields || fields.length === 0) return data;
69
87
 
70
- const fieldSet = new Set(fields);
88
+ const names = new Set();
89
+ const paths = new Set();
90
+ for (const field of fields) {
91
+ (field.includes('.') ? paths : names).add(field);
92
+ }
71
93
 
72
- function filterObject(obj) {
94
+ function filterObject(obj, path) {
73
95
  if (obj === null || obj === undefined) return obj;
74
96
  if (Array.isArray(obj)) {
75
- return obj.map(item => filterObject(item));
97
+ return obj.map(item => filterObject(item, path));
76
98
  }
77
99
  if (typeof obj !== 'object') return obj;
78
100
 
79
101
  const filtered = {};
80
102
  for (const key of Object.keys(obj)) {
81
- if (fieldSet.has(key)) {
103
+ const keyPath = path ? `${path}.${key}` : key;
104
+ if (names.has(key) || paths.has(keyPath)) {
82
105
  // Explicitly requested — include as-is
83
106
  filtered[key] = obj[key];
84
107
  } else if (typeof obj[key] === 'object' && obj[key] !== null) {
@@ -89,7 +112,7 @@ export function filterFields(data, fields) {
89
112
  const hasObjectElements = obj[key].length > 0 &&
90
113
  typeof obj[key][0] === 'object' && obj[key][0] !== null;
91
114
  if (hasObjectElements) {
92
- const nested = obj[key].map(item => filterObject(item))
115
+ const nested = obj[key].map(item => filterObject(item, keyPath))
93
116
  .filter(item => Object.keys(item).length > 0);
94
117
  if (nested.length > 0) {
95
118
  filtered[key] = nested;
@@ -97,7 +120,7 @@ export function filterFields(data, fields) {
97
120
  }
98
121
  } else {
99
122
  // Plain object — always recurse in case it wraps requested fields
100
- const nested = filterObject(obj[key]);
123
+ const nested = filterObject(obj[key], keyPath);
101
124
  if (nested !== null && nested !== undefined && Object.keys(nested).length > 0) {
102
125
  filtered[key] = nested;
103
126
  }
@@ -107,7 +130,7 @@ export function filterFields(data, fields) {
107
130
  return filtered;
108
131
  }
109
132
 
110
- return filterObject(data);
133
+ return filterObject(data, '');
111
134
  }
112
135
 
113
136
  /**
@@ -162,6 +185,10 @@ export function compactSchema(schema) {
162
185
  params_legend: '* = required',
163
186
  commands,
164
187
  globalOptions: Object.keys(schema.globalOptions).join(', '),
188
+ // Which commands cache, and how to control it. One rule rather than a flag
189
+ // repeated on every command — caching is a property of the request path,
190
+ // not of the individual command.
191
+ caching: schema.caching,
165
192
  chains: schema.chains,
166
193
  smartMoneyLabels: schema.smartMoneyLabels
167
194
  };
@@ -172,38 +199,72 @@ export function compactSchema(schema) {
172
199
  // subcommand, so it lives here rather than inline in parseArgs.
173
200
  export const VALUELESS_FLAGS = new Set([
174
201
  'pretty', 'help', 'version', 'table', 'no-retry', 'cache', 'no-cache', 'stream',
175
- 'enrich', 'full', 'human', 'enabled', 'disabled', 'expert', 'json', 'offline',
202
+ 'enrich', 'full', 'human', 'no-browser', 'api-key-stdin', 'enabled', 'disabled', 'expert', 'json', 'offline',
176
203
  'no-simulate', 'no-verify-outcome', 'no-revoke-excessive-allowance', 'dry-run',
177
204
  'send-api-key', 'all', 'max', 'gasless', 'auto-slippage', 'unsafe-no-password',
205
+ 'reveal', 'yes', 'paginate', 'debug',
178
206
  ]);
179
207
 
180
208
  export function parseArgs(args) {
181
209
  const result = { _: [], flags: {}, options: {} };
210
+
211
+ const addFlag = (key) => {
212
+ if (key in result.flags) {
213
+ if (!Array.isArray(result.flags[key])) result.flags[key] = [result.flags[key]];
214
+ result.flags[key].push(true);
215
+ } else {
216
+ result.flags[key] = true;
217
+ }
218
+ };
182
219
 
183
220
  for (let i = 0; i < args.length; i++) {
184
221
  const arg = args[i];
185
222
 
186
223
  if (arg.startsWith('--')) {
187
- const key = arg.slice(2);
188
- const next = args[i + 1];
224
+ const equalsIndex = arg.indexOf('=');
225
+ const inlineKey = equalsIndex === -1 ? null : arg.slice(2, equalsIndex);
226
+ // `--help=false` is neither help nor a meaningful false value: valueless
227
+ // switches only accept their bare spelling. Reject it instead of leaking
228
+ // a stale `flags['help=false']` key that no handler will ever inspect.
229
+ if (inlineKey !== null && VALUELESS_FLAGS.has(inlineKey)) {
230
+ throw new NansenError(`--${inlineKey} does not accept a value`, ErrorCode.INVALID_PARAMS);
231
+ }
232
+ // Value-taking options, including boolean options handled by
233
+ // resolveBooleanOption(), accept the conventional `--key=value` spelling.
234
+ const hasInlineValue = inlineKey !== null;
235
+ const key = hasInlineValue ? inlineKey : arg.slice(2);
236
+ const next = hasInlineValue ? arg.slice(equalsIndex + 1) : args[i + 1];
189
237
 
190
238
  if (VALUELESS_FLAGS.has(key)) {
239
+ // Repeating a switch is idempotent. Keeping the value strictly true
240
+ // avoids leaking `[true, true]` into consumers that use `=== true`.
191
241
  result.flags[key] = true;
192
242
  // `next !== undefined` rather than a truthiness check: an explicit empty
193
243
  // string is a real value, and skipping it here left `""` dangling to be
194
244
  // picked up as a positional arg on the next iteration.
195
- } else if (next !== undefined && (!next.startsWith('-') || /^-\d/.test(next))) {
196
- // Try to parse as JSON first (for objects/arrays/booleans),
197
- // but keep numeric strings as strings to avoid precision loss
198
- // and scientific notation for large integers (e.g. 1e+21).
199
- let parsedValue;
245
+ // An inline value was explicitly supplied and is always consumed, even
246
+ // when it begins with a dash; downstream option validation owns whether
247
+ // that value is meaningful. The dash guard applies only to two-token
248
+ // input, where `--key --next` denotes two separate arguments.
249
+ } else if (hasInlineValue || (next !== undefined && (!next.startsWith('-') || /^-\d/.test(next)))) {
250
+ // Try to parse as JSON so object/array options (`--filters '{}'`,
251
+ // `--order-by '[...]'`) arrive structured. Numbers stay strings to
252
+ // avoid precision loss and scientific notation for large integers
253
+ // (e.g. 1e+21). The bare keywords true/false/null stay strings too:
254
+ // no option takes a boolean or null *value*, so coercing them would
255
+ // silently retype a string option (`--sort true` used to become the
256
+ // boolean true). Boolean options read the strings 'true'/'false'
257
+ // through resolveBooleanOption().
258
+ let parsedValue = next;
200
259
  try {
201
260
  const parsed = JSON.parse(next);
202
- parsedValue = typeof parsed === 'number' ? next : parsed;
261
+ if (typeof parsed !== 'number' && typeof parsed !== 'boolean' && parsed !== null) {
262
+ parsedValue = parsed;
263
+ }
203
264
  } catch {
204
- parsedValue = next;
265
+ // Not JSON: keep the raw string.
205
266
  }
206
- i++;
267
+ if (!hasInlineValue) i++;
207
268
  // Accumulate repeated options into arrays (supports repeatable flags like --token, --subject)
208
269
  if (key in result.options) {
209
270
  if (!Array.isArray(result.options[key])) {
@@ -214,10 +275,10 @@ export function parseArgs(args) {
214
275
  result.options[key] = parsedValue;
215
276
  }
216
277
  } else {
217
- result.flags[key] = true;
278
+ addFlag(key);
218
279
  }
219
280
  } else if (arg.startsWith('-')) {
220
- result.flags[arg.slice(1)] = true;
281
+ addFlag(arg.slice(1));
221
282
  } else {
222
283
  result._.push(arg);
223
284
  }
@@ -319,6 +380,10 @@ function parseNonNegativeSafeIntegerOption(name, options, flags, defaultValue) {
319
380
  'non-negative safe integer',
320
381
  );
321
382
 
383
+ // Callers without an option or default intentionally receive undefined.
384
+ // Do not rely on JavaScript's `undefined < 0` coercion for that contract.
385
+ if (value === undefined) return undefined;
386
+
322
387
  if (value < 0) {
323
388
  throw new NansenError(
324
389
  `--${name} must be a non-negative safe integer; received: ${value}`,
@@ -329,6 +394,36 @@ function parseNonNegativeSafeIntegerOption(name, options, flags, defaultValue) {
329
394
  return value;
330
395
  }
331
396
 
397
+ function parsePositiveSafeIntegerOption(name, options, flags, defaultValue, { max } = {}) {
398
+ const value = parseSafeIntegerOption(
399
+ name,
400
+ options,
401
+ flags,
402
+ defaultValue,
403
+ 'positive safe integer',
404
+ );
405
+
406
+ // Keep the helper safe for future optional callers; the current pagination
407
+ // caller supplies DEFAULT_MAX_PAGES whenever this parser is activated.
408
+ if (value === undefined) return undefined;
409
+
410
+ if (value < 1) {
411
+ throw new NansenError(
412
+ `--${name} must be a positive safe integer; received: ${value}`,
413
+ ErrorCode.INVALID_PARAMS,
414
+ );
415
+ }
416
+
417
+ if (max !== undefined && value > max) {
418
+ throw new NansenError(
419
+ `--${name} must be at most ${max}; received: ${value}`,
420
+ ErrorCode.INVALID_PARAMS,
421
+ );
422
+ }
423
+
424
+ return value;
425
+ }
426
+
332
427
 
333
428
  function parseDaysOption(options, flags) {
334
429
  const days = parseNonNegativeSafeIntegerOption('days', options, flags, 30);
@@ -364,16 +459,9 @@ export function formatValue(val) {
364
459
  // Table formatter for human-readable output
365
460
  export function formatTable(data) {
366
461
  // Extract array of records from various response shapes
367
- let records = [];
368
- if (Array.isArray(data)) {
369
- records = data;
370
- } else if (data?.data && Array.isArray(data.data)) {
371
- records = data.data;
372
- } else if (data?.results && Array.isArray(data.results)) {
373
- records = data.results;
374
- } else if (data?.data?.results && Array.isArray(data.data.results)) {
375
- records = data.data.results;
376
- } else if (typeof data === 'object' && data !== null) {
462
+ const located = locateRows(data, { descriptive: true });
463
+ let records = located?.rows || [];
464
+ if (!located && typeof data === 'object' && data !== null) {
377
465
  // Single object - convert to array
378
466
  records = [data];
379
467
  }
@@ -436,16 +524,9 @@ export function formatTable(data) {
436
524
  */
437
525
  export function formatCsv(data) {
438
526
  // Extract array of records from various response shapes
439
- let records = [];
440
- if (Array.isArray(data)) {
441
- records = data;
442
- } else if (data?.data && Array.isArray(data.data)) {
443
- records = data.data;
444
- } else if (data?.results && Array.isArray(data.results)) {
445
- records = data.results;
446
- } else if (data?.data?.results && Array.isArray(data.data.results)) {
447
- records = data.data.results;
448
- } else if (typeof data === 'object' && data !== null) {
527
+ const located = locateRows(data, { descriptive: true });
528
+ let records = located?.rows || [];
529
+ if (!located && typeof data === 'object' && data !== null) {
449
530
  records = [data];
450
531
  }
451
532
 
@@ -469,21 +550,30 @@ export function formatCsv(data) {
469
550
  return lines.join('\n');
470
551
  }
471
552
 
553
+ // Render the error envelope for the non-JSON formats. CSV gets a real header
554
+ // row plus one record so the envelope stays machine-parseable; table keeps the
555
+ // leading `Error:` line and follows it with one `key: value` line per field, so
556
+ // code, status and details are not dropped on the way to the terminal.
557
+ function formatErrorText(data, { csv = false } = {}) {
558
+ if (csv) return formatCsv(data);
559
+ const lines = [`Error: ${data.error}`];
560
+ for (const [key, val] of Object.entries(data)) {
561
+ if (key === 'success' || key === 'error' || val == null) continue;
562
+ lines.push(`${key}: ${typeof val === 'object' ? JSON.stringify(val) : val}`);
563
+ }
564
+ return lines.join('\n');
565
+ }
566
+
472
567
  // Format output data (returns string, does not print)
473
568
  export function formatOutput(data, { pretty = false, table = false, csv = false } = {}) {
474
- if (csv) {
475
- if (data.success === false) {
476
- return { type: 'error', text: `Error: ${data.error}` };
477
- }
478
- const csvData = data.data || data;
479
- return { type: 'csv', text: formatCsv(csvData) };
480
- } else if (table) {
569
+ if (csv || table) {
481
570
  if (data.success === false) {
482
- return { type: 'error', text: `Error: ${data.error}` };
483
- } else {
484
- const tableData = data.data || data;
485
- return { type: 'table', text: formatTable(tableData) };
571
+ return { type: 'error', text: formatErrorText(data, { csv }) };
486
572
  }
573
+ const body = data.data || data;
574
+ return csv
575
+ ? { type: 'csv', text: formatCsv(body) }
576
+ : { type: 'table', text: formatTable(body) };
487
577
  } else if (pretty) {
488
578
  return { type: 'json', text: JSON.stringify(data, null, 2) };
489
579
  } else {
@@ -500,6 +590,10 @@ export const USAGE_ERROR_CODES = new Set(['MISSING_PARAM', 'MISSING_ARGS']);
500
590
 
501
591
  export function isUsageError(errorData, { pretty, table, csv, stream, isTTY }) {
502
592
  if (!USAGE_ERROR_CODES.has(errorData.code)) return false;
593
+ // API errors can map onto the same semantic code (for example the server's
594
+ // `missing_field` becomes MISSING_PARAM), but they are not local usage
595
+ // banners and must retain the structured envelope in every output mode.
596
+ if (errorData.status != null) return false;
503
597
  if (pretty || table || csv || stream) return false;
504
598
  return !!isTTY;
505
599
  }
@@ -528,17 +622,11 @@ export function formatError(error) {
528
622
  * Each record is output as a separate JSON line
529
623
  */
530
624
  export function formatStream(data) {
625
+ if (data?.success === false) return JSON.stringify(data);
531
626
  // Extract array of records from various response shapes
532
- let records = [];
533
- if (Array.isArray(data)) {
534
- records = data;
535
- } else if (data?.data && Array.isArray(data.data)) {
536
- records = data.data;
537
- } else if (data?.results && Array.isArray(data.results)) {
538
- records = data.results;
539
- } else if (data?.data?.results && Array.isArray(data.data.results)) {
540
- records = data.data.results;
541
- } else if (typeof data === 'object' && data !== null) {
627
+ const located = locateRows(data, { descriptive: true });
628
+ let records = located?.rows || [];
629
+ if (!located && typeof data === 'object' && data !== null) {
542
630
  // Single object - output as single line
543
631
  records = [data];
544
632
  }
@@ -622,7 +710,11 @@ async function enrichTransfers(result, apiInstance, chain) {
622
710
  const labelMap = {};
623
711
  for (const addr of addrs) {
624
712
  try {
625
- const labelsResult = await apiInstance.addressLabels({ address: addr, chain });
713
+ const labelsResult = await apiInstance.addressLabels({
714
+ address: addr,
715
+ chain,
716
+ requestOptions: { autoPaginate: false },
717
+ });
626
718
  labelMap[addr] = Array.isArray(labelsResult?.data)
627
719
  ? labelsResult.data.map(item => item.label)
628
720
  : labelsResult?.labels || [];
@@ -733,7 +825,11 @@ export async function batchProfile(api, params = {}) {
733
825
  }
734
826
  try {
735
827
  if (include.includes('labels')) {
736
- const labelsResult = await api.addressLabels({ address, chain });
828
+ const labelsResult = await api.addressLabels({
829
+ address,
830
+ chain,
831
+ requestOptions: { autoPaginate: false },
832
+ });
737
833
  entry.labels = Array.isArray(labelsResult?.data)
738
834
  ? labelsResult.data
739
835
  : labelsResult?.labels || [];
@@ -742,7 +838,11 @@ export async function batchProfile(api, params = {}) {
742
838
  entry.balance = await api.addressBalance({ address, chain });
743
839
  }
744
840
  if (include.includes('pnl')) {
745
- entry.pnl = await api.addressPnl({ address, chain });
841
+ entry.pnl = await api.addressPnl({
842
+ address,
843
+ chain,
844
+ requestOptions: { autoPaginate: false },
845
+ });
746
846
  }
747
847
  } catch (err) {
748
848
  entry.error = err.message;
@@ -753,19 +853,37 @@ export async function batchProfile(api, params = {}) {
753
853
  return { results, total: addresses.length, completed: results.filter(r => !r.error).length };
754
854
  }
755
855
 
756
- function normalizeTraceDepth(raw) {
856
+ function normalizeTraceDepth(raw, flags = {}) {
757
857
  const value = parseSafeIntegerOption(
758
858
  'depth',
759
859
  { depth: raw },
760
- {},
761
- 2,
860
+ flags,
762
861
  );
763
862
 
764
863
  return Math.max(1, Math.min(value, 5));
765
864
  }
766
865
 
866
+ // --width is the fan-out at every hop, so it multiplies with --depth: an
867
+ // unbounded width on a hub-style address (exchange, router) turns one
868
+ // invocation into hundreds of counterparties calls and credits. Clamp it the
869
+ // way --depth is clamped, and stop expanding the graph past MAX_TRACE_NODES
870
+ // as a backstop for the depth × width product.
871
+ const MAX_TRACE_WIDTH = 50;
872
+ const MAX_TRACE_NODES = 1000;
873
+
874
+ function normalizeTraceWidth(raw) {
875
+ const value = parseNonNegativeSafeIntegerOption(
876
+ 'width',
877
+ { width: raw },
878
+ {},
879
+ 10,
880
+ );
881
+
882
+ return Math.max(1, Math.min(value, MAX_TRACE_WIDTH));
883
+ }
884
+
767
885
  export async function traceCounterparties(api, params = {}) {
768
- let { address, chain = 'ethereum', depth = 2, width = 10, days = 30, delayMs = 1000 } = params;
886
+ let { address, chain = 'ethereum', depth = 2, depthFlags = {}, width = 10, days = 30, delayMs = 1000 } = params;
769
887
  if (!address) {
770
888
  throw new NansenError('address is required for trace', ErrorCode.MISSING_PARAM);
771
889
  }
@@ -784,13 +902,15 @@ export async function traceCounterparties(api, params = {}) {
784
902
  if (!validation.valid) {
785
903
  throw new NansenError(validation.error, ErrorCode.INVALID_ADDRESS);
786
904
  }
787
- const clampedDepth = normalizeTraceDepth(depth);
905
+ const clampedDepth = normalizeTraceDepth(depth, depthFlags);
906
+ const clampedWidth = normalizeTraceWidth(width);
788
907
  const visited = new Set();
789
908
  const nodes = [];
790
909
  const edges = [];
791
910
  const queue = [{ addr: address, hop: 0 }];
792
911
  visited.add(address);
793
912
  nodes.push(address);
913
+ let truncated = false;
794
914
 
795
915
  while (queue.length > 0) {
796
916
  const { addr, hop } = queue.shift();
@@ -799,11 +919,12 @@ export async function traceCounterparties(api, params = {}) {
799
919
  try {
800
920
  const result = await api.addressCounterparties({
801
921
  address: addr, chain, days,
802
- pagination: { page: 1, per_page: width },
922
+ pagination: { page: 1, per_page: clampedWidth },
923
+ requestOptions: { autoPaginate: false },
803
924
  });
804
925
 
805
926
  const counterparties = result?.data?.results || result?.counterparties || result?.data || [];
806
- const items = Array.isArray(counterparties) ? counterparties.slice(0, width) : [];
927
+ const items = Array.isArray(counterparties) ? counterparties.slice(0, clampedWidth) : [];
807
928
 
808
929
  for (const cp of items) {
809
930
  const cpAddr = cp.counterparty_address || cp.address || cp.counterparty;
@@ -817,6 +938,11 @@ export async function traceCounterparties(api, params = {}) {
817
938
  });
818
939
 
819
940
  if (!visited.has(cpAddr)) {
941
+ if (nodes.length >= MAX_TRACE_NODES) {
942
+ // The edge is still recorded; the node is just not expanded.
943
+ truncated = true;
944
+ continue;
945
+ }
820
946
  visited.add(cpAddr);
821
947
  nodes.push(cpAddr);
822
948
  queue.push({ addr: cpAddr, hop: hop + 1 });
@@ -830,9 +956,14 @@ export async function traceCounterparties(api, params = {}) {
830
956
  }
831
957
 
832
958
  return {
833
- root: address, chain, depth: clampedDepth,
959
+ root: address, chain, depth: clampedDepth, width: clampedWidth,
834
960
  nodes, edges,
835
- stats: { nodes_visited: nodes.length, edges_found: edges.length, max_depth_reached: Math.max(0, ...edges.map(e => e.hop)) },
961
+ stats: {
962
+ nodes_visited: nodes.length,
963
+ edges_found: edges.length,
964
+ max_depth_reached: Math.max(0, ...edges.map(e => e.hop)),
965
+ truncated,
966
+ },
836
967
  };
837
968
  }
838
969
 
@@ -849,47 +980,106 @@ export async function compareWallets(api, params = {}) {
849
980
  }
850
981
  }
851
982
 
852
- // Fetch counterparties and balances for both addresses
983
+ // Fetch counterparties and balances for both addresses. A failed request is
984
+ // recorded rather than treated as an empty result, so an auth or rate-limit
985
+ // error cannot masquerade as "no overlap" / "0 USD".
986
+ const settle = (promise) => promise.then(value => ({ value }), error => ({ error }));
853
987
  const [cp1, cp2] = await Promise.all([
854
- api.addressCounterparties({ address: addr1, chain, days }).catch(() => null),
855
- api.addressCounterparties({ address: addr2, chain, days }).catch(() => null),
988
+ settle(api.addressCounterparties({
989
+ address: addr1, chain, days, requestOptions: { autoPaginate: false },
990
+ })),
991
+ settle(api.addressCounterparties({
992
+ address: addr2, chain, days, requestOptions: { autoPaginate: false },
993
+ })),
856
994
  ]);
857
995
  await sleep(delayMs);
858
996
  const [bal1, bal2] = await Promise.all([
859
- api.addressBalance({ address: addr1, chain }).catch(() => null),
860
- api.addressBalance({ address: addr2, chain }).catch(() => null),
997
+ settle(api.addressBalance({ address: addr1, chain })),
998
+ settle(api.addressBalance({ address: addr2, chain })),
861
999
  ]);
862
1000
 
1001
+ const outcomes = [
1002
+ [addr1, 'counterparties', cp1], [addr2, 'counterparties', cp2],
1003
+ [addr1, 'balance', bal1], [addr2, 'balance', bal2],
1004
+ ];
1005
+ const errors = [];
1006
+ const failures = [];
1007
+ for (const [address, source, outcome] of outcomes) {
1008
+ if (outcome.error) {
1009
+ failures.push(outcome.error);
1010
+ errors.push({ address, source, code: outcome.error.code ?? 'UNKNOWN', message: outcome.error.message });
1011
+ }
1012
+ }
1013
+ if (failures.length === outcomes.length) {
1014
+ throw failures[0];
1015
+ }
1016
+
863
1017
  // Extract counterparty addresses
864
1018
  const extractCps = (result) => {
865
1019
  const list = result?.data?.results || result?.counterparties || result?.data || [];
866
1020
  return Array.isArray(list) ? list : [];
867
1021
  };
868
- const cps1 = extractCps(cp1);
869
- const cps2 = extractCps(cp2);
870
- const cpAddrs1 = new Set(cps1.map(c => c.counterparty_address || c.address || c.counterparty).filter(Boolean));
871
- const cpAddrs2 = new Set(cps2.map(c => c.counterparty_address || c.address || c.counterparty).filter(Boolean));
872
- const sharedCpAddrs = [...cpAddrs1].filter(a => cpAddrs2.has(a));
1022
+ let sharedCpAddrs = null;
1023
+ if (!cp1.error && !cp2.error) {
1024
+ const cpAddrs1 = new Set(extractCps(cp1.value).map(c => c.counterparty_address || c.address || c.counterparty).filter(Boolean));
1025
+ const cpAddrs2 = new Set(extractCps(cp2.value).map(c => c.counterparty_address || c.address || c.counterparty).filter(Boolean));
1026
+ sharedCpAddrs = [...cpAddrs1].filter(a => cpAddrs2.has(a));
1027
+ }
873
1028
 
874
1029
  // Extract token holdings
875
1030
  const extractTokens = (result) => {
876
1031
  const list = result?.data?.results || result?.balances || result?.data || [];
877
1032
  return Array.isArray(list) ? list : [];
878
1033
  };
879
- const tokens1 = extractTokens(bal1);
880
- const tokens2 = extractTokens(bal2);
881
- const tokenSyms1 = new Set(tokens1.map(t => t.token_symbol).filter(Boolean));
882
- const tokenSyms2 = new Set(tokens2.map(t => t.token_symbol).filter(Boolean));
883
- const sharedTokens = [...tokenSyms1].filter(s => tokenSyms2.has(s));
1034
+ const tokens1 = bal1.error ? null : extractTokens(bal1.value);
1035
+ const tokens2 = bal2.error ? null : extractTokens(bal2.value);
1036
+ let sharedTokens = null;
1037
+ if (tokens1 && tokens2) {
1038
+ // Two different contracts can share a symbol, so when both sides report a
1039
+ // token address the address decides. When either side has no address for
1040
+ // a token (some responses omit it for the native asset) the symbol is the
1041
+ // only identity available and is used instead.
1042
+ const addressOf = (t) => {
1043
+ const address = t.token_address || t.mint || t.address;
1044
+ return address ? String(address).toLowerCase() : null;
1045
+ };
1046
+ const symbolOf = (t) => (t.token_symbol ? String(t.token_symbol).toLowerCase() : null);
1047
+ const addresses2 = new Set(tokens2.map(addressOf).filter(Boolean));
1048
+ const symbols2 = new Set(tokens2.map(symbolOf).filter(Boolean));
1049
+ const symbolsWithoutAddress2 = new Set(
1050
+ tokens2.filter(t => !addressOf(t)).map(symbolOf).filter(Boolean)
1051
+ );
1052
+ const seen = new Set();
1053
+ sharedTokens = [];
1054
+ for (const t of tokens1) {
1055
+ const address = addressOf(t);
1056
+ const symbol = symbolOf(t);
1057
+ // With an address on both sides only the address counts. If either
1058
+ // side omits it (as some responses do for the native asset) a matching
1059
+ // symbol is taken as the same token.
1060
+ const matched = address
1061
+ ? addresses2.has(address) || (symbol && symbolsWithoutAddress2.has(symbol))
1062
+ : symbol && symbols2.has(symbol);
1063
+ const key = address || symbol;
1064
+ if (matched && !seen.has(key)) {
1065
+ seen.add(key);
1066
+ sharedTokens.push(t.token_symbol || address);
1067
+ }
1068
+ }
1069
+ }
1070
+ const totalUsd = (tokens) => tokens === null
1071
+ ? null
1072
+ : tokens.reduce((sum, t) => sum + (t.value_usd ?? t.balance_usd ?? 0), 0);
884
1073
 
885
1074
  return {
886
1075
  addresses: [addr1, addr2], chain,
887
1076
  shared_counterparties: sharedCpAddrs,
888
1077
  shared_tokens: sharedTokens,
889
1078
  balances: [
890
- { address: addr1, total_usd: tokens1.reduce((sum, t) => sum + (t.value_usd ?? t.balance_usd ?? 0), 0) },
891
- { address: addr2, total_usd: tokens2.reduce((sum, t) => sum + (t.value_usd ?? t.balance_usd ?? 0), 0) },
1079
+ { address: addr1, total_usd: totalUsd(tokens1) },
1080
+ { address: addr2, total_usd: totalUsd(tokens2) },
892
1081
  ],
1082
+ ...(errors.length > 0 && { incomplete: true, errors }),
893
1083
  };
894
1084
  }
895
1085
 
@@ -902,26 +1092,45 @@ USAGE: nansen <command> [subcommand] [options]
902
1092
  COMMANDS:
903
1093
  trade DEX swaps/bridges: quote, execute, bridge-status, limit-order
904
1094
  bridge Hyperliquid bridge: quote, execute, status (EVM <-> HL)
905
- perp Hyperliquid perps: order, cancel, close, leverage, positions
1095
+ perp Hyperliquid perps: order, cancel, close, leverage, transfer, approve-builder-fee, positions, orders, account, meta, screener, leaderboard
906
1096
  research analytics: smart-money, profiler, token, search, perp, portfolio
907
- wallet create, list, show, export, default, delete, forget-password
1097
+ wallet ${WALLET_SUBCOMMANDS.join(', ')}
908
1098
  agent Ask the Nansen AI research agent (fast/expert modes)
909
1099
  alerts list, create, update, toggle, delete
910
1100
  web search, fetch
911
1101
  mcp install/uninstall/verify the Nansen MCP server
912
- account Show API key status, plan, and remaining credits
913
- auth status — offline auth status: key source, wallets (no network)
914
- login Save API key (--human, NANSEN_API_KEY, or --api-key <key>)
915
- logout Remove saved API key
1102
+ account Check the effective credential, plan, and remaining credits (free)
1103
+ auth status — offline credential source and cached/unverified session metadata
1104
+ login Sign in through browser approval (--no-browser for remote terminals)
1105
+ logout Remove saved API authentication; preserve wallets
916
1106
  doctor Diagnostics: auth, wallets, caches, connectivity (--offline --json)
917
1107
  schema JSON schema for all commands (use "nansen schema <cmd>" for one)
918
1108
  completion Shell completions: bash, zsh, fish
919
- cache clear
1109
+ cache stats, clear
920
1110
  changelog --since <version> to filter
921
1111
 
922
- OPTIONS: --chain --limit --sort field:dir --fields a,b --days N --filters '{}'
1112
+ OPTIONS: --chain --limit --page N --sort field:dir --fields a,b --days N --filters '{}'
1113
+ PAGING: --paginate (alias --all) fetch every page, --max-pages N (default 10), --limit sets page size
923
1114
  FORMAT: --pretty --table --format csv --stream (NDJSON)
924
1115
  RETRY: --no-retry --retries N --cache --cache-ttl N
1116
+ DEBUG: --debug (or NANSEN_DEBUG=1) traces each request on stderr: method, URL,
1117
+ status, time-to-headers (TTFB), retries, request id. Never prints
1118
+ credentials or bodies.
1119
+
1120
+ AUTHENTICATION:
1121
+ nansen login Fresh browser approval, even with an existing key/session
1122
+ nansen login --no-browser Same approval without opening the browser
1123
+ nansen auth status Offline, cached/unverified; does not open session storage
1124
+ nansen account Free live check of the effective credential
1125
+ nansen login --human Explicit legacy key setup; also persists an injected env key
1126
+ nansen login --api-key-stdin Read a key from a pipe or file; never echo the key
1127
+ NANSEN_API_KEY overrides saved authentication.
1128
+ API keys and browser sessions can auto-pay supported HTTP 402 challenges under the same wallet controls and spending limits.
1129
+ Authentication failures never trigger payment; login verification and nansen account never auto-pay.
1130
+ Browser sessions renew automatically; uncertain renewal requires fresh login.
1131
+ Browser nansen:api sessions have API-key-equivalent account permissions; wallet signing is separate.
1132
+ Browser login needs native storage and enabled server admission; release gates remain open.
1133
+ Public API endpoints keep their usual account, plan and credit checks; MCP key export is separate.
925
1134
 
926
1135
  TRADING:
927
1136
  nansen trade quote --chain solana --from SOL --to USDC --amount 1000000000
@@ -944,10 +1153,10 @@ EXAMPLES:
944
1153
  nansen research profiler balance --address 0x... --chain ethereum
945
1154
 
946
1155
  DEPRECATED ALIASES (still work, will be removed in a future version):
947
- smart-money, profiler, token, search, perp, portfolio → use "nansen research <command>"
1156
+ smart-money, profiler, token, search, portfolio → use "nansen research <command>"
948
1157
  quote, execute → use "nansen trade <command>"
949
1158
 
950
- Research chains: ethereum, solana, base, bnb, arbitrum, polygon, optimism, avalanche, linea, scroll, mantle, ronin, sei, plasma, sonic, monad, hyperevm, iotaevm
1159
+ Research chains: ${SCHEMA.chains.join(', ')}
951
1160
  Trade chains: solana, base
952
1161
  Bridge chains: ethereum, base, arbitrum, polygon, bnb, hyperliquid
953
1162
  Labels: Fund, Smart Trader, 30D/90D/180D Smart Trader, Smart HL Perps Trader
@@ -958,6 +1167,46 @@ Skills: npx skills add nansen-ai/nansen-cli (agent-optimised docs per command gr
958
1167
  Telemetry: anonymous usage stats (commands, timing, errors). Perp order/close additionally send each leg's side, outcome, order id, shared submission id, and a SHA-256 wallet identifier. Raw wallet, price, size, and exchange error text are not sent. Disable: DO_NOT_TRACK=1
959
1168
  `;
960
1169
 
1170
+ // Usage text for the `cache` command group. Also the answer to "which commands
1171
+ // cache?" — caching is decided by the request path, so the rule lives here (and
1172
+ // in schema.json under `caching`) rather than being repeated per command.
1173
+ export const CACHE_HELP = `nansen cache — inspect and clear the caches this CLI keeps on disk
1174
+
1175
+ SUBCOMMANDS:
1176
+ stats [--json] What each cache holds: entries, size, age, effective TTL
1177
+ clear [target] Delete cached entries (default target: responses)
1178
+
1179
+ CLEAR TARGETS:
1180
+ responses API responses saved when --cache is passed (default)
1181
+ cost-map Per-endpoint credit costs, refreshed every 24h
1182
+ update-check Latest published version, refreshed every 24h
1183
+ all All three
1184
+
1185
+ WHAT CACHES:
1186
+ Caching is off by default and opt-in per invocation with --cache. With it on,
1187
+ every read the CLI makes through the Nansen API client is served from and
1188
+ written to the response cache — that is all of "nansen research ...", plus
1189
+ "alerts list" and "alerts get".
1190
+ Never cached: account, web search, web fetch, alerts create/update/toggle/delete,
1191
+ agent (streamed), every trade, bridge, wallet and mcp command, and perp trading.
1192
+ The analytics commands "perp screener" and "perp leaderboard" are cached.
1193
+
1194
+ CACHE OPTIONS (for any command):
1195
+ --cache Enable caching for this invocation
1196
+ --no-cache Bypass the cache for this invocation (or NANSEN_NO_CACHE=1)
1197
+ --cache-ttl <seconds> Non-negative safe integer TTL (default: 300; 0 disables reads)
1198
+
1199
+ EXAMPLES:
1200
+ nansen cache stats
1201
+ nansen cache stats --json --pretty
1202
+ nansen cache clear
1203
+ nansen cache clear all
1204
+
1205
+ Saved trade quotes are not a cache and are never touched by "cache clear": they
1206
+ expire on their own, and an unexecuted quote is still spendable. Credentials,
1207
+ wallets and config are never changed by this command. CLI startup loads the saved
1208
+ config as usual.`;
1209
+
961
1210
  // Usage text for the `trade` command group. Shared by the trade handler and the
962
1211
  // --help path in runCLI, so `nansen trade`, `nansen trade <sub> --help`, and the
963
1212
  // deprecated top-level `quote`/`execute --help` all show the same usage.
@@ -972,7 +1221,7 @@ SUBCOMMANDS:
972
1221
  USAGE:
973
1222
  nansen trade quote --chain <chain> --from <token> --to <token> --amount <units> [--wallet <name>]
974
1223
  nansen trade quote --chain <chain> --to-chain <chain> --from <token> --to <token> --amount <units>
975
- nansen trade execute --quote <quoteId> [--wallet <name>]
1224
+ nansen trade execute --quote <quoteId> [--wallet <name>] [--dry-run] [--yes]
976
1225
  nansen trade bridge-status --tx-hash <hash> --from-chain <chain> --to-chain <chain>
977
1226
  nansen trade limit-order <create|list|cancel|update> [options]
978
1227
 
@@ -989,6 +1238,13 @@ WALLET:
989
1238
  --wallet <name> Use a named wallet, or "walletconnect" / "wc" for WalletConnect.
990
1239
  Defaults to the default local wallet if omitted.
991
1240
 
1241
+ BEFORE BROADCASTING (execute only):
1242
+ --dry-run Validate and print what would be sent, then stop. Nothing is
1243
+ signed or broadcast and the quote stays usable. Exits 0.
1244
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1). The prompt
1245
+ only appears when stdin is a terminal — agents, CI and pipes run
1246
+ unprompted either way. Declining exits 1 with nothing signed.
1247
+
992
1248
  SYMBOLS:
993
1249
  Common tokens resolve automatically: SOL, ETH, USDC, USDT, WETH
994
1250
  Raw addresses are also accepted.
@@ -1051,19 +1307,92 @@ export async function prompt(question, hidden = false, { input = process.stdin,
1051
1307
  });
1052
1308
  }
1053
1309
 
1310
+ // Confirmation prompts belong to the CLI adapter rather than trade/bridge
1311
+ // core. EOF and Ctrl+C resolve as the safe default ("no") so a closed input
1312
+ // cannot leave an irreversible command hanging forever.
1313
+ export async function promptForConfirmation(question, { input = process.stdin, output = process.stderr } = {}) {
1314
+ const rl = readline.createInterface({ input, output });
1315
+ return new Promise((resolve, reject) => {
1316
+ let settled = false;
1317
+ const finish = (answer) => {
1318
+ if (settled) return;
1319
+ settled = true;
1320
+ rl.close();
1321
+ resolve(answer);
1322
+ };
1323
+ const fail = (error) => {
1324
+ if (settled) return;
1325
+ settled = true;
1326
+ rl.close();
1327
+ reject(error);
1328
+ };
1329
+
1330
+ rl.once('close', () => finish(''));
1331
+ rl.once('SIGINT', () => finish(''));
1332
+ rl.once('error', fail);
1333
+ rl.question(question, finish);
1334
+ });
1335
+ }
1336
+
1337
+ // `token screener --search` filters client-side, so it can only find a token
1338
+ // among the candidate rows the API returned. These helpers describe that window
1339
+ // as `_meta.search: { query, searched, matched, complete }` so a short or empty
1340
+ // result can be told apart from "the token ranks below the rows we fetched".
1341
+ function locatePaginationSummary(result) {
1342
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
1343
+ if (isObject(result?.pagination)) return result.pagination;
1344
+ if (isObject(result?.data?.pagination)) return result.data.pagination;
1345
+ return null;
1346
+ }
1347
+
1348
+ function describeSearchWindow({ query, candidates, matched, perPage, summary }) {
1349
+ let complete;
1350
+ if (typeof summary?.complete === 'boolean') {
1351
+ // --paginate traversal summary (auto-paginate.js): false when --max-pages
1352
+ // stopped the walk before the server ran out of rows. It also carries the
1353
+ // first page's stale is_last_page, so it has to be checked first.
1354
+ complete = summary.complete;
1355
+ } else if (typeof summary?.is_last_page === 'boolean') {
1356
+ // Server metadata on the single candidate page.
1357
+ complete = summary.is_last_page;
1358
+ } else {
1359
+ // No metadata: a full page means the API may hold more rows beyond it.
1360
+ complete = candidates.length < perPage;
1361
+ }
1362
+ return { query, searched: candidates.length, matched, complete };
1363
+ }
1364
+
1365
+ function searchWindowNote(searchMeta, summary, paginateAll) {
1366
+ const rows = `${searchMeta.searched} screener row${searchMeta.searched === 1 ? '' : 's'}`;
1367
+ if (paginateAll) {
1368
+ const pages = Number.isInteger(summary?.pages_fetched)
1369
+ ? ` after ${summary.pages_fetched} candidate page${summary.pages_fetched === 1 ? '' : 's'} (--max-pages)`
1370
+ : '';
1371
+ const resume = Number.isInteger(summary?.next_page) ? ` or resume with --page ${summary.next_page}` : '';
1372
+ return `Note: --search stopped${pages} with ${rows} checked; tokens beyond them were not searched (_meta.search.complete: false). Raise --max-pages${resume}.`;
1373
+ }
1374
+ return `Note: --search matched against only the first ${rows}; tokens ranked below them were not searched (_meta.search.complete: false). Widen the window with --limit <n> (max 1000) or --paginate, or narrow the candidates with --filters.`;
1375
+ }
1376
+
1054
1377
  // Build command handlers (returns object with handler functions)
1055
1378
  export function buildCommands(deps = {}) {
1056
1379
  // Allow dependency injection for testing
1057
1380
  const {
1058
1381
  api: _api = null,
1382
+ // Password/API-key input belongs to login and may be hidden. Confirmation
1383
+ // is a separate contract: callers must opt into it explicitly so this
1384
+ // prompt can never be reused for an irreversible yes/no decision.
1059
1385
  promptFn = prompt,
1386
+ confirmationPromptFn,
1060
1387
  log = console.log,
1061
- errorOutput: _errorOutput = console.error,
1388
+ errorOutput = console.error,
1062
1389
  NansenAPIClass: _NansenAPIClass = NansenAPI,
1063
- saveConfigFn = saveConfig,
1064
- deleteConfigFn = deleteConfig,
1390
+ authState = defaultAuthState(),
1391
+ browserLoginFn = browserLogin,
1065
1392
  getConfigFileFn = getConfigFile,
1066
- isTTY = process.stdin.isTTY,
1393
+ stdoutTTY = deps.isTTY ?? process.stdout.isTTY,
1394
+ stdinTTY = deps.isTTY ?? process.stdin.isTTY,
1395
+ stdin = process.stdin,
1067
1396
  env = process.env
1068
1397
  } = deps;
1069
1398
 
@@ -1121,14 +1450,9 @@ export function buildCommands(deps = {}) {
1121
1450
  throw new NansenError('At least one query is required. Usage: nansen web search "bitcoin price" --num-results 5', ErrorCode.MISSING_PARAM);
1122
1451
  }
1123
1452
  let numResults;
1124
- if (options['num-results'] !== undefined) {
1125
- const numResultsRaw = parseInt(options['num-results'], 10);
1126
- if (Number.isNaN(numResultsRaw)) {
1127
- // Non-numeric — fall back to API default
1128
- numResults = undefined;
1129
- } else if (numResultsRaw >= 1 && numResultsRaw <= 20) {
1130
- numResults = numResultsRaw;
1131
- } else {
1453
+ if (options['num-results'] !== undefined || flags['num-results']) {
1454
+ numResults = parseSafeIntegerOption('num-results', options, flags, undefined, 'whole number between 1 and 20');
1455
+ if (numResults < 1 || numResults > 20) {
1132
1456
  throw new NansenError('--num-results must be between 1 and 20', ErrorCode.INVALID_PARAMS);
1133
1457
  }
1134
1458
  }
@@ -1181,29 +1505,25 @@ export function buildCommands(deps = {}) {
1181
1505
  },
1182
1506
 
1183
1507
  'login': async (args, apiInstance, flags, options) => {
1184
- if (flags.help || flags.h) {
1185
- log('nansen login - Save your Nansen API key\n');
1186
- log('USAGE:');
1187
- log(' nansen login --human (interactive prompt; key never enters shell history)');
1188
- log(' nansen login (uses NANSEN_API_KEY when already set)');
1189
- log(' nansen login --api-key <key> (literal key IS recorded in shell history)\n');
1190
- log('OPTIONS:');
1191
- log(' --api-key <key> Your Nansen API key (recorded in shell history — prefer --human)');
1192
- log(' --human Enable interactive prompt');
1193
- log(' --help Show this help\n');
1194
- log('Setting a literal key in a command may record it in shell history.');
1195
- log('Get your API key at: https://app.nansen.ai/auth/agent-setup');
1196
- return;
1508
+ if ('api-key-stdin' in options) throw new CommandError('--api-key-stdin does not accept a value.', 'INVALID_PARAMS');
1509
+ const fromStdin = flags['api-key-stdin'] === true;
1510
+ if (fromStdin && (args.length || flags.human || flags['no-browser'] || flags['api-key'] || 'api-key' in options)) {
1511
+ throw new CommandError('--api-key-stdin cannot be combined with arguments, --api-key, --human, or --no-browser.', 'INVALID_PARAMS');
1197
1512
  }
1513
+ if (flags['api-key']) throw new CommandError('--api-key requires a value.', 'MISSING_PARAM');
1514
+ if ('api-key' in options && typeof options['api-key'] !== 'string') throw new CommandError('--api-key must be a single key string.', 'INVALID_PARAMS');
1515
+ if (!fromStdin && !flags.human && options['api-key'] === undefined) {
1516
+ return browserLoginFn({ flags, env, isTTY: stdoutTTY, log, errorOutput, state: authState });
1517
+ }
1518
+ if (flags['no-browser']) throw new CommandError('--no-browser cannot be combined with legacy key setup.', 'INVALID_PARAMS');
1519
+ let apiKey = fromStdin ? await readApiKeyInput(stdin, stdinTTY) : options['api-key'];
1198
1520
 
1199
- let apiKey = options['api-key'];
1200
-
1201
- if (!apiKey) {
1202
- apiKey = process.env.NANSEN_API_KEY;
1521
+ if (apiKey === undefined) {
1522
+ apiKey = env.NANSEN_API_KEY?.trim() || undefined;
1203
1523
  }
1204
1524
 
1205
- if (!apiKey && flags.human) {
1206
- if (!isTTY) {
1525
+ if (apiKey === undefined && flags.human) {
1526
+ if (!stdinTTY) {
1207
1527
  throw new CommandError('--human requires an interactive terminal. Set NANSEN_API_KEY in the environment (or pass --api-key <key>, which is recorded in shell history).', 'NOT_A_TTY', {
1208
1528
  error: 'NOT_A_TTY',
1209
1529
  message: '--human requires an interactive terminal. Set NANSEN_API_KEY in the environment (or pass --api-key <key>, which is recorded in shell history).',
@@ -1226,73 +1546,84 @@ export function buildCommands(deps = {}) {
1226
1546
  });
1227
1547
  }
1228
1548
 
1229
- // Verify API key before saving
1230
- const NansenAPIClass = _NansenAPIClass;
1231
- const testApi = new NansenAPIClass(apiKey.trim(), undefined, {
1232
- retry: { maxRetries: 2 },
1233
- cache: { enabled: false }
1234
- });
1235
-
1236
1549
  let accountInfo;
1550
+ let cleanup;
1551
+ const baseUrl = authConfigView(env).baseUrl;
1552
+ const attempt = await authState.begin({ preflight: false });
1237
1553
  try {
1238
- accountInfo = await testApi.getAccount();
1239
- } catch (error) {
1240
- if (error.code === ErrorCode.UNAUTHORIZED) {
1241
- throw new CommandError('The API key is not valid.', 'INVALID_API_KEY', {
1242
- error: 'INVALID_API_KEY',
1243
- message: 'The API key is not valid.',
1244
- resolution: ['Check or rotate your key at https://app.nansen.ai/api?tab=api'],
1554
+ // Verify API key before saving
1555
+ const NansenAPIClass = _NansenAPIClass;
1556
+ const testApi = new NansenAPIClass(apiKey.trim(), baseUrl, {
1557
+ allowPayment: false,
1558
+ redactAuthDiagnostics: fromStdin,
1559
+ retry: { maxRetries: 2 },
1560
+ cache: { enabled: false }
1561
+ });
1562
+
1563
+ try {
1564
+ accountInfo = await testApi.getAccount();
1565
+ } catch (error) {
1566
+ if (error.code === ErrorCode.UNAUTHORIZED) {
1567
+ throw new CommandError('The API key is not valid.', 'INVALID_API_KEY', {
1568
+ error: 'INVALID_API_KEY',
1569
+ message: 'The API key is not valid.',
1570
+ resolution: ['Check or rotate your key at https://app.nansen.ai/api?tab=api'],
1571
+ });
1572
+ }
1573
+ // Restore signal from the STRUCTURED error code only — never from
1574
+ // error.message, which can echo the upstream response body (and the key
1575
+ // with it). A transient failure shouldn't read as "check your key".
1576
+ let message = 'Could not verify API key.';
1577
+ let resolution = ['Check your internet connection', 'Try again'];
1578
+ if (error.code === ErrorCode.RATE_LIMITED) {
1579
+ message = 'Rate limited while verifying the API key.';
1580
+ resolution = ['Wait a moment, then retry explicit key setup: nansen login --human'];
1581
+ } else if (error.code === ErrorCode.SERVER_ERROR || error.code === ErrorCode.SERVICE_UNAVAILABLE) {
1582
+ message = 'The Nansen API is unavailable right now, so the key could not be verified.';
1583
+ resolution = ['Try again shortly'];
1584
+ } else if (error.code === ErrorCode.TIMEOUT) {
1585
+ message = 'Timed out verifying the API key.';
1586
+ resolution = ['Check your connection', 'Try again'];
1587
+ }
1588
+ throw new CommandError(message, 'VERIFICATION_FAILED', {
1589
+ error: 'VERIFICATION_FAILED',
1590
+ message,
1591
+ resolution,
1245
1592
  });
1246
1593
  }
1247
- // Restore signal from the STRUCTURED error code only — never from
1248
- // error.message, which can echo the upstream response body (and the key
1249
- // with it). A transient failure shouldn't read as "check your key".
1250
- let message = 'Could not verify API key.';
1251
- let resolution = ['Check your internet connection', 'Try again'];
1252
- if (error.code === ErrorCode.RATE_LIMITED) {
1253
- message = 'Rate limited while verifying the API key.';
1254
- resolution = ['Wait a moment, then run nansen login again'];
1255
- } else if (error.code === ErrorCode.SERVER_ERROR || error.code === ErrorCode.SERVICE_UNAVAILABLE) {
1256
- message = 'The Nansen API is unavailable right now, so the key could not be verified.';
1257
- resolution = ['Try again shortly'];
1258
- } else if (error.code === ErrorCode.TIMEOUT) {
1259
- message = 'Timed out verifying the API key.';
1260
- resolution = ['Check your connection', 'Try again'];
1261
- }
1262
- throw new CommandError(message, 'VERIFICATION_FAILED', {
1263
- error: 'VERIFICATION_FAILED',
1264
- message,
1265
- resolution,
1266
- });
1267
- }
1268
1594
 
1269
- // Key is valid - now save
1270
- saveConfigFn({
1271
- apiKey: apiKey.trim(),
1272
- baseUrl: 'https://api.nansen.ai'
1273
- });
1595
+ const result = await authState.install(attempt, { apiKey: apiKey.trim(), baseUrl });
1596
+ cleanup = result.cleanup;
1597
+ if (!fromStdin || !flags.json) for (const message of cleanupMessage(cleanup)) log(message);
1598
+ } finally { await authState.finish(attempt); }
1599
+ const blankEnvKey = env.NANSEN_API_KEY !== undefined && !env.NANSEN_API_KEY.trim();
1600
+ if (fromStdin && flags.json) {
1601
+ log(JSON.stringify({ event: 'saved', effective_source: env.NANSEN_API_KEY !== undefined ? 'env' : 'config', environment_key_blank: blankEnvKey, cleanup }));
1602
+ return;
1603
+ }
1604
+ if (env.NANSEN_API_KEY !== undefined) log(blankEnvKey
1605
+ ? 'NANSEN_API_KEY is blank. Commands will fail until you unset it or supply a valid environment key.'
1606
+ : 'Commands still use NANSEN_API_KEY. Unset it to use the saved credential.');
1274
1607
 
1275
1608
  log(`✓ Saved to ${getConfigFileFn()}\n`);
1276
- if (accountInfo?.plan) {
1609
+ // Verification responses may reflect the submitted key. Stdin login
1610
+ // prints only local status, including when upstream fields look harmless.
1611
+ if (!fromStdin && accountInfo?.plan) {
1277
1612
  log(`Plan: ${accountInfo.plan}`);
1278
1613
  }
1279
- if (accountInfo?.credits_remaining !== undefined) {
1614
+ if (!fromStdin && accountInfo?.credits_remaining !== undefined) {
1280
1615
  log(`Credits remaining: ${accountInfo.credits_remaining}`);
1281
1616
  }
1282
- log('\nYou can now use the Nansen CLI. Try:');
1617
+ log(blankEnvKey ? '\nUnset NANSEN_API_KEY to use the saved credential, then try:' : '\nYou can now use the Nansen CLI. Try:');
1283
1618
  log(' nansen research token screener --chain solana --pretty');
1284
1619
  },
1285
1620
 
1286
1621
  'logout': async (_args, _apiInstance, _flags, _options) => {
1287
- const deleted = deleteConfigFn();
1288
- if (deleted) {
1289
- log(`✓ Removed ${getConfigFileFn()}`);
1290
- } else {
1291
- log('No saved credentials found');
1292
- }
1293
- if (env.NANSEN_API_KEY) {
1294
- log('Warning: NANSEN_API_KEY remains active. Run: unset NANSEN_API_KEY');
1295
- }
1622
+ const result = await authState.logout();
1623
+ if (result.cleanup.some(item => item.local === 'incomplete')) log('Saved authentication selection cleared; secure-store deletion incomplete.');
1624
+ else log(result.removed ? 'Local credentials removed.' : 'No saved credentials found.');
1625
+ for (const message of cleanupMessage(result.cleanup)) log(message);
1626
+ if (env.NANSEN_API_KEY !== undefined) log('Warning: NANSEN_API_KEY remains active. Run: unset NANSEN_API_KEY');
1296
1627
  },
1297
1628
 
1298
1629
  'help': async (_args, _apiInstance, _flags, _options) => {
@@ -1320,8 +1651,10 @@ export function buildCommands(deps = {}) {
1320
1651
  // silently comparing as if it were version 0.0.0, which would show
1321
1652
  // every entry rather than flag the typo.
1322
1653
  if (!/^v?\d+(\.\d+){0,2}$/.test(String(since))) {
1323
- log(`Invalid --since value "${since}": expected a version like 1.43 or 1.43.0.`);
1324
- return;
1654
+ throw new NansenError(
1655
+ `Invalid --since value "${since}": expected a version like 1.43 or 1.43.0.`,
1656
+ ErrorCode.INVALID_PARAMS
1657
+ );
1325
1658
  }
1326
1659
  // Show only entries from the given version onwards
1327
1660
  const lines = content.split('\n');
@@ -1368,32 +1701,44 @@ export function buildCommands(deps = {}) {
1368
1701
  return compactSchema(SCHEMA);
1369
1702
  },
1370
1703
 
1371
- 'cache': async (args, _apiInstance, _flags, _options) => {
1372
- const subcommand = args[0] || 'help';
1373
-
1704
+ 'cache': async (args, _apiInstance, flags, options) => {
1705
+ const subcommand = args[0] ?? 'help';
1706
+
1374
1707
  const handlers = {
1708
+ 'stats': () => {
1709
+ // The TTL this invocation would apply, so "expired" means what the
1710
+ // next call would actually discard.
1711
+ const responseTtlSeconds = parseNonNegativeSafeIntegerOption('cache-ttl', options, flags, 300);
1712
+ const stats = collectCacheStats({ responseTtlSeconds });
1713
+ if (flags.json) return stats;
1714
+ log(formatCacheStats(stats));
1715
+ },
1375
1716
  'clear': () => {
1376
- const count = clearCache();
1377
- log(`✓ Cleared ${count} cached responses`);
1378
- log(` Cache dir: ${getCacheDir()}`);
1717
+ // Deleting local state needs an explicit target. The default is the
1718
+ // response cache alone — the one cache that is always safely
1719
+ // refetchable — and wiping everything requires saying "all".
1720
+ const target = args[1] ?? 'responses';
1721
+ log(formatCacheClear(clearCaches(target)));
1379
1722
  },
1380
1723
  'help': () => {
1381
- log('Cache Management\n');
1382
- log('USAGE:');
1383
- log(' nansen cache clear Clear all cached responses\n');
1384
- log('CACHE OPTIONS (for any command):');
1385
- log(' --cache Enable caching for this session');
1386
- log(' --no-cache Bypass cache for this request');
1387
- log(' --cache-ttl <seconds> Set non-negative safe integer cache TTL (default: 300)');
1724
+ log(CACHE_HELP);
1388
1725
  }
1389
1726
  };
1390
-
1391
- if (!handlers[subcommand]) {
1392
- log(`Unknown cache subcommand: ${subcommand}`);
1393
- handlers['help']();
1394
- return;
1727
+
1728
+ if (!Object.hasOwn(handlers, subcommand)) {
1729
+ throw new NansenError(
1730
+ `Unknown cache subcommand: ${subcommand}. Use one of: stats, clear`,
1731
+ ErrorCode.INVALID_PARAMS,
1732
+ );
1733
+ }
1734
+
1735
+ const maxArgs = subcommand === 'clear' ? 2 : 1;
1736
+ if (args.length > maxArgs) {
1737
+ throw new NansenError(
1738
+ `Too many cache arguments. Use: nansen cache ${subcommand}${subcommand === 'clear' ? ' [responses|cost-map|update-check|all]' : ''}`,
1739
+ ErrorCode.INVALID_PARAMS,
1740
+ );
1395
1741
  }
1396
-
1397
1742
  return handlers[subcommand]();
1398
1743
  },
1399
1744
 
@@ -1404,7 +1749,7 @@ export function buildCommands(deps = {}) {
1404
1749
  const subcommand = args[0] || 'help';
1405
1750
  const chain = options.chain || 'solana';
1406
1751
  const chains = options.chains || [chain];
1407
- const filters = options.filters || {};
1752
+ const filters = parseObjectOption(options.filters, 'filters');
1408
1753
  const orderBy = parseSort(options.sort, options['order-by']);
1409
1754
  const pagination = buildPagination(options);
1410
1755
 
@@ -1422,7 +1767,7 @@ export function buildCommands(deps = {}) {
1422
1767
  const handlers = {
1423
1768
  'netflow': () => apiInstance.smartMoneyNetflow({ chains, filters, orderBy, pagination }),
1424
1769
  'dex-trades': () => apiInstance.smartMoneyDexTrades({ chains, filters, orderBy, pagination }),
1425
- 'perp-trades': () => apiInstance.smartMoneyPerpTrades({ filters, orderBy, pagination, onlyNewPositions: options['only-new-positions'] ?? flags['only-new-positions'] }),
1770
+ 'perp-trades': () => apiInstance.smartMoneyPerpTrades({ filters, orderBy, pagination, onlyNewPositions: resolveBooleanOption(options, flags, 'only-new-positions') }),
1426
1771
  'holdings': () => apiInstance.smartMoneyHoldings({ chains, filters, orderBy, pagination }),
1427
1772
  'dcas': () => apiInstance.smartMoneyDcas({ filters, orderBy, pagination }),
1428
1773
  'historical-holdings': () => apiInstance.smartMoneyHistoricalHoldings({ chains, filters, orderBy, pagination, days }),
@@ -1460,7 +1805,7 @@ export function buildCommands(deps = {}) {
1460
1805
  throw new NansenError(err.message, ErrorCode.INVALID_ADDRESS);
1461
1806
  }
1462
1807
  }
1463
- const filters = options.filters || {};
1808
+ const filters = parseObjectOption(options.filters, 'filters');
1464
1809
  const orderBy = parseSort(options.sort, options['order-by']);
1465
1810
  const pagination = buildPagination(options);
1466
1811
  const days = [
@@ -1520,22 +1865,16 @@ export function buildCommands(deps = {}) {
1520
1865
  }
1521
1866
  const parsedInclude = parseCsvOption(options.include, 'include');
1522
1867
  const include = (parsedInclude && parsedInclude.length > 0) ? parsedInclude : ['labels', 'balance'];
1523
- const delayMs = options.delay ? parseInt(options.delay) : 1000;
1868
+ const delayMs = parseNonNegativeSafeIntegerOption('delay', options, flags, 1000);
1524
1869
  return batchProfile(apiInstance, { addresses, chain, include, delayMs });
1525
1870
  },
1526
1871
  'trace': () => {
1527
1872
  rejectBlankOption(options.delay, 'delay', '1000');
1528
1873
  rejectBlankOption(options.depth, 'depth', '2');
1529
- if (flags.depth) {
1530
- throw new NansenError(
1531
- '--depth requires a safe integer value',
1532
- ErrorCode.INVALID_PARAMS,
1533
- );
1534
- }
1535
- const depth = options.depth ?? 2;
1874
+ const depth = options.depth;
1536
1875
  const width = parseNonNegativeSafeIntegerOption('width', options, flags, 10);
1537
- const delayMs = options.delay ? parseInt(options.delay) : 1000;
1538
- return traceCounterparties(apiInstance, { address, chain, depth, width, days, delayMs });
1876
+ const delayMs = parseNonNegativeSafeIntegerOption('delay', options, flags, 1000);
1877
+ return traceCounterparties(apiInstance, { address, chain, depth, depthFlags: flags, width, days, delayMs });
1539
1878
  },
1540
1879
  'compare': () => {
1541
1880
  const addrs = parseAddressList(options.addresses);
@@ -1572,7 +1911,7 @@ export function buildCommands(deps = {}) {
1572
1911
  const tokenSymbol = options.symbol || options['token-symbol'];
1573
1912
  const chains = options.chains || [chain];
1574
1913
  const timeframe = options.timeframe || '24h';
1575
- const filters = options.filters || {};
1914
+ const filters = parseObjectOption(options.filters, 'filters');
1576
1915
  const orderBy = parseSort(options.sort, options['order-by']);
1577
1916
  const pagination = buildPagination(options);
1578
1917
  const days = [
@@ -1588,13 +1927,13 @@ export function buildCommands(deps = {}) {
1588
1927
  : 30;
1589
1928
 
1590
1929
  // Convenience filter for smart money only
1591
- const onlySmartMoney = options['smart-money'] || flags['smart-money'] || false;
1930
+ const onlySmartMoney = resolveBooleanOption(options, flags, 'smart-money') ?? false;
1592
1931
  if (onlySmartMoney) {
1593
1932
  filters.include_smart_money_labels = filters.include_smart_money_labels ||
1594
1933
  ['Fund', 'Smart Trader', '30D Smart Trader', '90D Smart Trader', '180D Smart Trader'];
1595
1934
  }
1596
1935
 
1597
- const includeStablecoins = options['include-stablecoins'] ?? flags['include-stablecoins'];
1936
+ const includeStablecoins = resolveBooleanOption(options, flags, 'include-stablecoins');
1598
1937
  if (includeStablecoins !== undefined) {
1599
1938
  filters.include_stablecoins = includeStablecoins;
1600
1939
  }
@@ -1605,25 +1944,65 @@ export function buildCommands(deps = {}) {
1605
1944
  'info': () => apiInstance.tokenInformation({ tokenAddress, chain, timeframe: options.timeframe }),
1606
1945
  'screener': async () => {
1607
1946
  const search = options.search;
1608
- // When searching, fetch more results to filter from (API has no server-side search)
1609
- const searchPagination = search
1610
- ? { page: 1, per_page: Math.max(500, pagination?.per_page || 0) }
1947
+ if (search !== undefined && typeof search !== 'string') {
1948
+ throw new NansenError('--search must be a string', ErrorCode.INVALID_PARAMS);
1949
+ }
1950
+ // When searching, fetch more results to filter from (API has no server-side search).
1951
+ // --page/--limit are applied client-side to the filtered list, so the
1952
+ // candidate fetch has to cover every page up to the requested one.
1953
+ const requestedLimit = pagination?.per_page || 100;
1954
+ const requestedPage = pagination?.page || 1;
1955
+ const paginateAll = flags.paginate || flags.all;
1956
+ const searchPagination = search
1957
+ ? {
1958
+ page: paginateAll ? requestedPage : 1,
1959
+ // A normal client-side search widens its one candidate fetch.
1960
+ // With --paginate, keep --limit as the server page size: the
1961
+ // traversal already fetches up to --max-pages separately
1962
+ // billed pages, so silently multiplying each one to 500 would
1963
+ // make the flag much more expensive than documented.
1964
+ per_page: paginateAll
1965
+ ? requestedLimit
1966
+ : Math.max(500, requestedPage * requestedLimit),
1967
+ }
1611
1968
  : pagination;
1612
1969
  const result = await apiInstance.tokenScreener({ chains, timeframe, filters, orderBy, pagination: searchPagination });
1613
1970
  if (search) {
1614
1971
  const q = search.toLowerCase();
1615
- const requestedLimit = pagination?.per_page || 100;
1616
- const filterArr = (arr) => arr.filter(t =>
1617
- (t.token_symbol && t.token_symbol.toLowerCase().includes(q)) ||
1618
- (t.token_name && t.token_name.toLowerCase().includes(q)) ||
1619
- (t.token_address && t.token_address.toLowerCase() === q)
1620
- ).slice(0, requestedLimit);
1972
+ const offset = (requestedPage - 1) * requestedLimit;
1621
1973
  // Handle nested response shapes: {data: [...]} or {data: {data: [...]}}
1974
+ let candidates;
1975
+ let rebuild;
1622
1976
  if (Array.isArray(result?.data)) {
1623
- return { ...result, data: filterArr(result.data) };
1624
- } else if (result?.data?.data && Array.isArray(result.data.data)) {
1625
- return { ...result, data: { ...result.data, data: filterArr(result.data.data) } };
1977
+ candidates = result.data;
1978
+ rebuild = rows => ({ ...result, data: rows });
1979
+ } else if (Array.isArray(result?.data?.data)) {
1980
+ candidates = result.data.data;
1981
+ rebuild = rows => ({ ...result, data: { ...result.data, data: rows } });
1982
+ } else {
1983
+ return result;
1626
1984
  }
1985
+ const matching = candidates.filter(t =>
1986
+ (t.token_symbol && t.token_symbol.toLowerCase().includes(q)) ||
1987
+ (t.token_name && t.token_name.toLowerCase().includes(q)) ||
1988
+ (t.token_address && t.token_address.toLowerCase() === q)
1989
+ );
1990
+ // Filtering only replaces the row array. With --paginate, the
1991
+ // preserved pagination metadata describes candidate traversal,
1992
+ // not the number of client-side matches.
1993
+ const filtered = rebuild(paginateAll ? matching : matching.slice(offset, offset + requestedLimit));
1994
+ // The search only saw the candidates fetched above, so say how far it
1995
+ // looked: `complete: false` means the API had more rows past the
1996
+ // window and a token that is missing here may simply rank below it.
1997
+ const summary = locatePaginationSummary(result);
1998
+ const searchMeta = describeSearchWindow({
1999
+ query: search, candidates, matched: matching.length, perPage: searchPagination.per_page, summary,
2000
+ });
2001
+ filtered._meta = { ...(result._meta || {}), search: searchMeta };
2002
+ // stderr, so --fields/--table/--csv/--stream callers that never see
2003
+ // _meta still learn the search was cut short.
2004
+ if (!searchMeta.complete) errorOutput(searchWindowNote(searchMeta, summary, paginateAll));
2005
+ return filtered;
1627
2006
  }
1628
2007
  return result;
1629
2008
  },
@@ -1640,7 +2019,14 @@ export function buildCommands(deps = {}) {
1640
2019
  },
1641
2020
  'who-bought-sold': () => {
1642
2021
  const date = parseDateOption(options.date, days, flags.date);
1643
- const buyOrSell = (options['buy-or-sell'] || 'BUY').toUpperCase();
2022
+ const buyOrSellRaw = options['buy-or-sell'];
2023
+ if (buyOrSellRaw !== undefined && typeof buyOrSellRaw !== 'string') {
2024
+ throw new NansenError('--buy-or-sell must be BUY or SELL', ErrorCode.INVALID_PARAMS);
2025
+ }
2026
+ const buyOrSell = (buyOrSellRaw || 'BUY').toUpperCase();
2027
+ if (buyOrSell !== 'BUY' && buyOrSell !== 'SELL') {
2028
+ throw new NansenError('--buy-or-sell must be BUY or SELL', ErrorCode.INVALID_PARAMS);
2029
+ }
1644
2030
  return apiInstance.tokenWhoBoughtSold({ tokenAddress, chain, buyOrSell, filters, orderBy, pagination, days, date });
1645
2031
  },
1646
2032
  'flow-intelligence': () => apiInstance.tokenFlowIntelligence({ tokenAddress, chain, timeframe: options.timeframe || '1d' }),
@@ -1659,7 +2045,7 @@ export function buildCommands(deps = {}) {
1659
2045
  },
1660
2046
  'top-tokens': () => {
1661
2047
  const marketCapGroup = options['market-cap'] || options['market-cap-group'];
1662
- const limit = options.limit ? parseInt(options.limit) : undefined;
2048
+ const limit = parseNonNegativeSafeIntegerOption('limit', options, flags);
1663
2049
  return apiInstance.topTokens({ marketCapGroup, limit });
1664
2050
  },
1665
2051
  'help': () => ({
@@ -1699,7 +2085,17 @@ export function buildCommands(deps = {}) {
1699
2085
 
1700
2086
  // Enrich transfers with Nansen labels for from/to addresses
1701
2087
  if (subcommand === 'transfers' && (options.enrich || flags.enrich)) {
1702
- result = await enrichTransfers(result, apiInstance, chain);
2088
+ // Label lookups are auxiliary requests and may themselves carry a
2089
+ // pagination body. Preserve the primary transfer traversal metadata
2090
+ // that runCLI reports after the command completes.
2091
+ const transferPaginationMeta = apiInstance.paginatedResponseMeta;
2092
+ const transferPaginationEndpoint = apiInstance.paginatedEndpoint;
2093
+ try {
2094
+ result = await enrichTransfers(result, apiInstance, chain);
2095
+ } finally {
2096
+ apiInstance.paginatedResponseMeta = transferPaginationMeta;
2097
+ apiInstance.paginatedEndpoint = transferPaginationEndpoint;
2098
+ }
1703
2099
  }
1704
2100
 
1705
2101
  return result;
@@ -1729,7 +2125,7 @@ export function buildCommands(deps = {}) {
1729
2125
  'perp': async (args, apiInstance, flags, options) => {
1730
2126
  rejectBlankOption(options.days, 'days', '30');
1731
2127
  const subcommand = args[0] || 'help';
1732
- const filters = options.filters || {};
2128
+ const filters = parseObjectOption(options.filters, 'filters');
1733
2129
  const orderBy = parseSort(options.sort, options['order-by']);
1734
2130
  const pagination = buildPagination(options);
1735
2131
  const days = ['screener', 'leaderboard'].includes(subcommand)
@@ -1874,7 +2270,8 @@ export function buildCommands(deps = {}) {
1874
2270
  };
1875
2271
 
1876
2272
  // 'trade' delegates to quote/execute from buildTradingCommands and limit-order from buildLimitOrderCommands
1877
- const tradingCmds = buildTradingCommands(deps);
2273
+ const executionDeps = { ...deps, promptFn: confirmationPromptFn };
2274
+ const tradingCmds = buildTradingCommands(executionDeps);
1878
2275
  const limitOrderCmds = buildLimitOrderCommands(deps);
1879
2276
  cmds['trade'] = async (args, apiInstance, flags, options) => {
1880
2277
  const sub = args[0];
@@ -1912,7 +2309,7 @@ USAGE:
1912
2309
  };
1913
2310
 
1914
2311
  // 'bridge' delegates to quote/execute/status from buildBridgeCommands
1915
- const bridgeCmds = buildBridgeCommands(deps);
2312
+ const bridgeCmds = buildBridgeCommands(executionDeps);
1916
2313
  cmds['bridge'] = async (args, apiInstance, flags, options) => {
1917
2314
  const sub = args[0];
1918
2315
  if (!sub || sub === 'help') {
@@ -1925,9 +2322,14 @@ SUBCOMMANDS:
1925
2322
 
1926
2323
  USAGE:
1927
2324
  nansen bridge quote --from-chain base --to-chain hyperliquid --from-token USDC --amount 1000000
1928
- nansen bridge execute --quote <quoteId>
2325
+ nansen bridge execute --quote <quoteId> [--dry-run] [--yes]
1929
2326
  nansen bridge status --request-id <id>
1930
2327
 
2328
+ BEFORE BROADCASTING (execute only):
2329
+ --dry-run Validate and print what would be signed, then stop. Exits 0.
2330
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1). The prompt only
2331
+ appears when stdin is a terminal; declining exits 1, signing nothing.
2332
+
1931
2333
  SUPPORTED ROUTES:
1932
2334
  ${formatBridgeRoutes()}`);
1933
2335
  return;
@@ -2011,7 +2413,16 @@ export const RESEARCH_CATEGORY_ALIASES = {
2011
2413
 
2012
2414
  // Generate help text for a specific subcommand using SCHEMA
2013
2415
  export function generateSubcommandHelp(command, subcommand, prefix = null) {
2014
- const cmdSchema = SCHEMA.commands[command] || SCHEMA.commands.research.subcommands[command];
2416
+ // `perp` is both a top-level trading command and a research category, and
2417
+ // the two have different subcommands. Look in both places and use whichever
2418
+ // actually holds this subcommand (top-level wins when both do) instead of
2419
+ // stopping at the first schema whose *name* matches — that made
2420
+ // `research perp screener --help` fall back to listing the category's
2421
+ // subcommands, i.e. telling the caller to run the command they just ran.
2422
+ const topSchema = SCHEMA.commands[command];
2423
+ const researchSchema = SCHEMA.commands.research.subcommands[command];
2424
+ const fromResearch = !topSchema?.subcommands?.[subcommand] && Boolean(researchSchema?.subcommands?.[subcommand]);
2425
+ const cmdSchema = fromResearch ? researchSchema : topSchema || researchSchema;
2015
2426
  if (!cmdSchema) return null;
2016
2427
 
2017
2428
  const subSchema = cmdSchema.subcommands?.[subcommand];
@@ -2042,7 +2453,7 @@ export function generateSubcommandHelp(command, subcommand, prefix = null) {
2042
2453
 
2043
2454
  const exampleValues = { address: '0x...', token: '0x...', query: '"term"', symbol: 'BTC', date: '2024-01-01' };
2044
2455
  const chain = subSchema.options?.chain?.default || 'solana';
2045
- const cmdPrefix = prefix || (DEPRECATED_TO_RESEARCH.has(command) ? `research ${command}` : command);
2456
+ const cmdPrefix = prefix || (fromResearch || DEPRECATED_TO_RESEARCH.has(command) ? `research ${command}` : command);
2046
2457
  let example = subSchema.examples?.[0] || `nansen ${cmdPrefix} ${subcommand}`;
2047
2458
  if (!subSchema.examples?.length && subSchema.options) {
2048
2459
  for (const [name, opt] of Object.entries(subSchema.options)) {
@@ -2057,6 +2468,31 @@ export function generateSubcommandHelp(command, subcommand, prefix = null) {
2057
2468
  return lines.join('\n');
2058
2469
  }
2059
2470
 
2471
+ function emitResponseMetadata(api, errorOutput) {
2472
+ if (!api) return;
2473
+ const responseMeta = api.paginatedResponseMeta || api.lastResponseMeta;
2474
+ const lowCredits = creditWarning(responseMeta);
2475
+ if (lowCredits) errorOutput(lowCredits);
2476
+ for (const notice of noticeWarnings(responseMeta)) errorOutput(notice);
2477
+
2478
+ // An aggregate belongs to the primary paginated endpoint even if a composite
2479
+ // handler made auxiliary requests afterward and changed lastEndpoint.
2480
+ const endpoint = api.paginatedResponseMeta ? api.paginatedEndpoint : api.lastEndpoint;
2481
+ const charged = creditsCharged(responseMeta, endpoint);
2482
+ if (charged?.source === 'header') {
2483
+ const paginationMeta = responseMeta?.pagination;
2484
+ let scope = 'this call';
2485
+ if (paginationMeta?.cachedPages > 0 && paginationMeta.livePages > 0) {
2486
+ scope = `${paginationMeta.livePages} live of ${paginationMeta.pagesFetched} page requests`;
2487
+ } else if (paginationMeta?.livePages > 1) scope = `${paginationMeta.livePages} page requests`;
2488
+ else if (paginationMeta?.livePages === 1) scope = '1 page request';
2489
+ else if (paginationMeta?.livePages === 0) scope = 'cached traversal';
2490
+ errorOutput(`Credits: ${charged.cost} (${scope})`);
2491
+ } else if (charged?.source === 'estimate') {
2492
+ errorOutput(`Credits: ~${charged.estimate.free} free / ${charged.estimate.pro} pro (estimated)`);
2493
+ }
2494
+ }
2495
+
2060
2496
  // Run CLI with given args (returns result, allows custom output/exit handlers)
2061
2497
  export async function runCLI(rawArgs, deps = {}) {
2062
2498
  const {
@@ -2065,12 +2501,55 @@ export async function runCLI(rawArgs, deps = {}) {
2065
2501
  exit = process.exit,
2066
2502
  NansenAPIClass = NansenAPI,
2067
2503
  commandOverrides = {},
2068
- // Injectable so tests can exercise both renderings; defaults to the real
2069
- // terminal, which is false under a pipe or in CI.
2504
+ // Output TTY controls human-vs-structured error rendering. Keep the
2505
+ // existing `isTTY` seam for callers/tests that inject both terminal states.
2070
2506
  isTTY = process.stdout.isTTY,
2507
+ env = process.env,
2071
2508
  } = deps;
2072
2509
 
2073
- const { _: positional, flags, options } = parseArgs(rawArgs);
2510
+ // Command-layer interactivity is intentionally governed by stdin. Besides
2511
+ // trade/bridge confirmation, buildCommands' existing `login --human` prompt
2512
+ // consumes this same signal; stdout may be redirected while a person still
2513
+ // answers either prompt on stdin. The separate `isTTY` destructured above
2514
+ // remains the stdout signal for human-vs-structured error rendering. Callers
2515
+ // can split the signals with `isInputTTY`; legacy `isTTY` injection still
2516
+ // drives both for compatibility.
2517
+ const isInputTTY = deps.isInputTTY ?? (deps.isTTY ?? process.stdin.isTTY);
2518
+
2519
+ // Pass the CLI-owned terminal seams into command modules. Keeping these out
2520
+ // of core means direct/library callers are non-interactive unless they
2521
+ // explicitly provide a prompt.
2522
+ const inputInteractiveDeps = {
2523
+ ...deps,
2524
+ isTTY: isInputTTY,
2525
+ stdoutTTY: isTTY,
2526
+ stdinTTY: isInputTTY,
2527
+ promptFn: deps.promptFn ?? prompt,
2528
+ confirmationPromptFn: deps.confirmationPromptFn ?? promptForConfirmation,
2529
+ confirmationLog: deps.confirmationLog ?? errorOutput,
2530
+ };
2531
+ const topLevelTradingDeps = {
2532
+ ...inputInteractiveDeps,
2533
+ promptFn: inputInteractiveDeps.confirmationPromptFn,
2534
+ };
2535
+
2536
+ let parsed;
2537
+ let api;
2538
+ let responseMetadataEmitted = false;
2539
+ const emitResponseMetadataOnce = () => {
2540
+ if (responseMetadataEmitted) return;
2541
+ responseMetadataEmitted = true;
2542
+ emitResponseMetadata(api, errorOutput);
2543
+ };
2544
+ try {
2545
+ parsed = parseArgs(rawArgs);
2546
+ } catch (error) {
2547
+ const errorData = formatError(error);
2548
+ output(formatOutput(errorData).text);
2549
+ exit(1);
2550
+ return { type: 'error', data: errorData };
2551
+ }
2552
+ const { _: positional, flags, options } = parsed;
2074
2553
 
2075
2554
  // Resolve command aliases
2076
2555
  const rawCommand = positional[0] || 'help';
@@ -2078,27 +2557,34 @@ export async function runCLI(rawArgs, deps = {}) {
2078
2557
  const subArgs = positional.slice(1);
2079
2558
  const subcommand = subArgs[0];
2080
2559
 
2081
-
2560
+ // `--debug` turns on the request trace for the rest of the process. Set
2561
+ // before anything can make a request, and only when the flag is present so
2562
+ // NANSEN_DEBUG=1 still decides on its own when the flag is absent.
2563
+ if (flags.debug) setDebugEnabled(true);
2082
2564
 
2083
2565
  const pretty = flags.pretty || flags.p;
2084
2566
  const table = flags.table || flags.t;
2085
2567
  const stream = flags.stream || flags.s;
2086
2568
  const csv = options.format === 'csv';
2087
2569
 
2088
- // `auth` and `doctor --offline` promise zero network activity — that
2089
- // contract covers the background update-check fetch and telemetry too,
2090
- // not just the command's own requests.
2570
+ // Commands in this set promise zero network activity. That includes update
2571
+ // checks, cost-map refreshes and telemetry, not just their primary work.
2572
+ // `cache` belongs here specifically so inspecting or clearing caches cannot
2573
+ // recreate update/telemetry state during the same invocation.
2091
2574
  const isMcpUsage = command === 'mcp' && (subcommand !== 'verify' || flags.help || flags.h);
2092
- // `completion` renders from the checked-in schema — no network, and its
2093
- // stdout is piped straight into a shell, so keep the update check out of it.
2094
- const isOfflineCommand = command === 'auth' || (command === 'doctor' && flags.offline) || isMcpUsage || command === 'completion';
2095
- const trackSucceeded = isOfflineCommand ? async () => {} : trackCommandSucceeded;
2096
- const trackFailed = isOfflineCommand ? async () => {} : trackCommandFailed;
2575
+ const isAuthMutation = command === 'login' || command === 'logout';
2576
+ const isOfflineCommand = command === 'auth'
2577
+ || (command === 'doctor' && flags.offline)
2578
+ || isMcpUsage
2579
+ || command === 'completion'
2580
+ || command === 'cache';
2581
+ const trackSucceeded = isOfflineCommand ? async () => {} : isAuthMutation ? metadata => trackAuthCommand({ ...metadata, command }) : trackCommandSucceeded;
2582
+ const trackFailed = isOfflineCommand ? async () => {} : isAuthMutation ? metadata => trackAuthCommand({ ...metadata, command, failed: true }) : trackCommandFailed;
2097
2583
 
2098
2584
  // Update check (read cached result + schedule background refresh)
2099
- const updateNotification = getUpdateNotification(VERSION);
2100
- const upgradeNotice = getUpgradeNotice(VERSION);
2101
- if (!isOfflineCommand) scheduleUpdateCheck();
2585
+ const updateNotification = isOfflineCommand ? null : getUpdateNotification(VERSION);
2586
+ const upgradeNotice = isOfflineCommand ? null : getUpgradeNotice(VERSION);
2587
+ if (!isOfflineCommand && !isAuthMutation) scheduleUpdateCheck();
2102
2588
  const notify = () => {
2103
2589
  if (upgradeNotice) errorOutput(upgradeNotice);
2104
2590
  if (updateNotification) errorOutput(updateNotification);
@@ -2113,7 +2599,11 @@ export async function runCLI(rawArgs, deps = {}) {
2113
2599
 
2114
2600
  // mcp prints its own output via `log`; runCLI callers inject their stdout
2115
2601
  // sink as `output`, so map it across (an explicit `log` dep still wins).
2116
- 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 };
2602
+ // Only execute/login handlers consume the stdin-interactivity seam. Other
2603
+ // modules retain their existing deps: notably wallet export interprets
2604
+ // `isTTY` as stdout visibility when deciding whether to warn about printing
2605
+ // private keys, so substituting the stdin signal there changes its semantics.
2606
+ 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 };
2117
2607
 
2118
2608
  if (flags.version || flags.v) {
2119
2609
  output(VERSION);
@@ -2123,7 +2613,7 @@ export async function runCLI(rawArgs, deps = {}) {
2123
2613
  if (command === 'help' || flags.help || flags.h) {
2124
2614
  // Help for an offline command still owes the zero-network contract: the
2125
2615
  // cost-map refresh fetches the OpenAPI spec and writes ~/.nansen/cost-map.json.
2126
- if (!isOfflineCommand) await refreshCostMapIfStale();
2616
+ if (!isOfflineCommand && !isAuthMutation) await refreshCostMapIfStale();
2127
2617
  // Check for subcommand-specific help: nansen <command> <subcommand> --help
2128
2618
  if (flags.help || flags.h) {
2129
2619
  // Handle 'research <category> <sub> --help' (3-level)
@@ -2176,8 +2666,8 @@ export async function runCLI(rawArgs, deps = {}) {
2176
2666
  }
2177
2667
  }
2178
2668
  // Then try command-level help (list subcommands)
2179
- // Skip for 'trade'/'alerts' — let the handler show its own usage
2180
- const cmdSchemaLookup = command !== 'trade' && command !== 'alerts' && command !== 'agent' && (SCHEMA.commands[command] || SCHEMA.commands.research.subcommands[command]);
2669
+ // Skip for 'trade'/'alerts'/'cache' — let the handler show its own usage
2670
+ const cmdSchemaLookup = command !== 'trade' && command !== 'alerts' && command !== 'agent' && command !== 'cache' && (SCHEMA.commands[command] || SCHEMA.commands.research.subcommands[command]);
2181
2671
  if (command && cmdSchemaLookup) {
2182
2672
  const cmdSchema = cmdSchemaLookup;
2183
2673
  const lines = [`${command} — ${cmdSchema.description}`];
@@ -2207,9 +2697,8 @@ export async function runCLI(rawArgs, deps = {}) {
2207
2697
  // Prevents destructive commands like logout from running when user just wants help
2208
2698
  if (commands[command]) {
2209
2699
  const simpleHelp = {
2210
- 'logout': 'nansen logout — Remove saved API key from ~/.nansen/config.json',
2211
2700
  'schema': 'nansen schema [command] [--pretty] — Show JSON schema for all commands (or a specific command)',
2212
- 'cache': 'nansen cache clear — Clear the API response cache',
2701
+ 'cache': CACHE_HELP,
2213
2702
  };
2214
2703
  if (simpleHelp[command]) {
2215
2704
  output(simpleHelp[command]);
@@ -2271,7 +2760,10 @@ export async function runCLI(rawArgs, deps = {}) {
2271
2760
  // Configure cache options
2272
2761
  const cacheTtl = parseNonNegativeSafeIntegerOption('cache-ttl', options, flags, 300);
2273
2762
  const cacheOptions = {
2274
- enabled: flags['cache'] && !flags['no-cache'],
2763
+ // NANSEN_NO_CACHE is the flagless form of --no-cache, for callers that
2764
+ // cannot edit the command line (a wrapper script or agent harness that
2765
+ // always passes --cache). Both are a veto, never an enable.
2766
+ enabled: flags['cache'] && !flags['no-cache'] && env.NANSEN_NO_CACHE !== '1',
2275
2767
  ttl: cacheTtl
2276
2768
  };
2277
2769
 
@@ -2279,7 +2771,16 @@ export async function runCLI(rawArgs, deps = {}) {
2279
2771
  if (options['x402-payment-signature']) {
2280
2772
  defaultHeaders['Payment-Signature'] = options['x402-payment-signature'];
2281
2773
  }
2282
- const api = new NansenAPIClass(undefined, undefined, { retry: retryOptions, cache: cacheOptions, defaultHeaders });
2774
+ api = new NansenAPIClass(undefined, undefined, { retry: retryOptions, cache: cacheOptions, defaultHeaders, authState: inputInteractiveDeps.authState });
2775
+
2776
+ // --all aliases --paginate; wrapping api.request gives every list handler
2777
+ // the same max-pages bound while leaving non-list requests untouched.
2778
+ if (flags.paginate || flags.all) {
2779
+ const maxPages = parsePositiveSafeIntegerOption(
2780
+ 'max-pages', options, flags, DEFAULT_MAX_PAGES, { max: MAX_PAGES_LIMIT },
2781
+ );
2782
+ enableAutoPagination(api, { maxPages });
2783
+ }
2283
2784
 
2284
2785
  // Deprecated top-level aliases otherwise run silently (the notice was only
2285
2786
  // shown in --help). Warn on stderr so it doesn't pollute parsed stdout.
@@ -2308,18 +2809,7 @@ export async function runCLI(rawArgs, deps = {}) {
2308
2809
  // stderr so it never contaminates the JSON on stdout that agents parse.
2309
2810
  // Placed before every return path below so it fires for operational
2310
2811
  // commands too, which print their own output and return undefined.
2311
- const lowCredits = creditWarning(api.lastResponseMeta);
2312
- if (lowCredits) errorOutput(lowCredits);
2313
- for (const notice of noticeWarnings(api.lastResponseMeta)) errorOutput(notice);
2314
-
2315
- // What this call cost — authoritative header when the API sent one, else
2316
- // the cached spec estimate. stderr only, so stdout JSON stays pure.
2317
- const charged = creditsCharged(api.lastResponseMeta, api.lastEndpoint);
2318
- if (charged?.source === 'header') {
2319
- errorOutput(`Credits: ${charged.cost} (this call)`);
2320
- } else if (charged?.source === 'estimate') {
2321
- errorOutput(`Credits: ~${charged.estimate.free} free / ${charged.estimate.pro} pro (estimated)`);
2322
- }
2812
+ emitResponseMetadataOnce();
2323
2813
 
2324
2814
  // Commands that handle their own output return undefined
2325
2815
  if (result === undefined) {
@@ -2365,6 +2855,9 @@ export async function runCLI(rawArgs, deps = {}) {
2365
2855
  await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
2366
2856
  return { type: csv ? 'csv' : 'success', data: result };
2367
2857
  } catch (error) {
2858
+ // A failed later page can still have incurred charges on earlier pages.
2859
+ // Emit the aggregate on stderr before serializing the unchanged error.
2860
+ emitResponseMetadataOnce();
2368
2861
  // Unified error envelope across all command families (perp/bridge/trade):
2369
2862
  // every failure serializes through formatError as
2370
2863
  // {success:false, error, code, status, details}. A CommandError's structured