nansen-cli 1.46.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 (77) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +129 -14
  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 +8 -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 +5 -2
  35. package/skills/nansen-wallet-manager/SKILL.md +11 -9
  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 +202 -104
  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 +126 -21
  51. package/src/cache-inspect.js +345 -0
  52. package/src/cli.js +470 -197
  53. package/src/commands/agent.js +15 -7
  54. package/src/commands/completion.js +2 -15
  55. package/src/commands/mcp.js +20 -18
  56. package/src/cost-cache.js +16 -2
  57. package/src/debug.js +348 -0
  58. package/src/doctor.js +22 -45
  59. package/src/hl-action.js +41 -13
  60. package/src/mcp-client-config.js +169 -0
  61. package/src/mcp-client-config.json +17 -0
  62. package/src/mcp-verify.js +6 -5
  63. package/src/perp.js +41 -0
  64. package/src/privy.js +12 -12
  65. package/src/response-meta.js +56 -1
  66. package/src/rpc-urls.js +9 -11
  67. package/src/schema.json +185 -8
  68. package/src/semver.js +23 -4
  69. package/src/swap-simulation.js +35 -30
  70. package/src/telemetry.js +20 -0
  71. package/src/trading.js +266 -29
  72. package/src/transfer.js +53 -6
  73. package/src/update-check.js +9 -1
  74. package/src/wallet.js +107 -17
  75. package/src/walletconnect-trading.js +24 -5
  76. package/src/x402-svm.js +123 -64
  77. package/src/x402.js +46 -14
package/src/cli.js CHANGED
@@ -1,9 +1,12 @@
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';
9
+ import { NansenAPI, NansenError, CommandError, ErrorCode, getConfigFile, validateAddress, normalizeAddress, sleep } from './api.js';
7
10
  import { buildWalletCommands, WALLET_SUBCOMMANDS } from './wallet.js';
8
11
  import { buildBridgeCommands, formatBridgeRoutes } from './bridge.js';
9
12
  import { buildPerpCommands } from './perp.js';
@@ -15,6 +18,7 @@ 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
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
 
@@ -179,6 +185,10 @@ export function compactSchema(schema) {
179
185
  params_legend: '* = required',
180
186
  commands,
181
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,
182
192
  chains: schema.chains,
183
193
  smartMoneyLabels: schema.smartMoneyLabels
184
194
  };
@@ -189,10 +199,10 @@ export function compactSchema(schema) {
189
199
  // subcommand, so it lives here rather than inline in parseArgs.
190
200
  export const VALUELESS_FLAGS = new Set([
191
201
  'pretty', 'help', 'version', 'table', 'no-retry', 'cache', 'no-cache', 'stream',
192
- 'enrich', 'full', 'human', 'enabled', 'disabled', 'expert', 'json', 'offline',
202
+ 'enrich', 'full', 'human', 'no-browser', 'api-key-stdin', 'enabled', 'disabled', 'expert', 'json', 'offline',
193
203
  'no-simulate', 'no-verify-outcome', 'no-revoke-excessive-allowance', 'dry-run',
194
204
  'send-api-key', 'all', 'max', 'gasless', 'auto-slippage', 'unsafe-no-password',
195
- 'reveal', 'yes',
205
+ 'reveal', 'yes', 'paginate', 'debug',
196
206
  ]);
197
207
 
198
208
  export function parseArgs(args) {
@@ -370,6 +380,10 @@ function parseNonNegativeSafeIntegerOption(name, options, flags, defaultValue) {
370
380
  'non-negative safe integer',
371
381
  );
372
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
+
373
387
  if (value < 0) {
374
388
  throw new NansenError(
375
389
  `--${name} must be a non-negative safe integer; received: ${value}`,
@@ -380,6 +394,36 @@ function parseNonNegativeSafeIntegerOption(name, options, flags, defaultValue) {
380
394
  return value;
381
395
  }
382
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
+
383
427
 
384
428
  function parseDaysOption(options, flags) {
385
429
  const days = parseNonNegativeSafeIntegerOption('days', options, flags, 30);
@@ -415,16 +459,9 @@ export function formatValue(val) {
415
459
  // Table formatter for human-readable output
416
460
  export function formatTable(data) {
417
461
  // Extract array of records from various response shapes
418
- let records = [];
419
- if (Array.isArray(data)) {
420
- records = data;
421
- } else if (data?.data && Array.isArray(data.data)) {
422
- records = data.data;
423
- } else if (data?.results && Array.isArray(data.results)) {
424
- records = data.results;
425
- } else if (data?.data?.results && Array.isArray(data.data.results)) {
426
- records = data.data.results;
427
- } 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) {
428
465
  // Single object - convert to array
429
466
  records = [data];
430
467
  }
@@ -487,16 +524,9 @@ export function formatTable(data) {
487
524
  */
488
525
  export function formatCsv(data) {
489
526
  // Extract array of records from various response shapes
490
- let records = [];
491
- if (Array.isArray(data)) {
492
- records = data;
493
- } else if (data?.data && Array.isArray(data.data)) {
494
- records = data.data;
495
- } else if (data?.results && Array.isArray(data.results)) {
496
- records = data.results;
497
- } else if (data?.data?.results && Array.isArray(data.data.results)) {
498
- records = data.data.results;
499
- } 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) {
500
530
  records = [data];
501
531
  }
502
532
 
@@ -592,17 +622,11 @@ export function formatError(error) {
592
622
  * Each record is output as a separate JSON line
593
623
  */
594
624
  export function formatStream(data) {
625
+ if (data?.success === false) return JSON.stringify(data);
595
626
  // Extract array of records from various response shapes
596
- let records = [];
597
- if (Array.isArray(data)) {
598
- records = data;
599
- } else if (data?.data && Array.isArray(data.data)) {
600
- records = data.data;
601
- } else if (data?.results && Array.isArray(data.results)) {
602
- records = data.results;
603
- } else if (data?.data?.results && Array.isArray(data.data.results)) {
604
- records = data.data.results;
605
- } 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) {
606
630
  // Single object - output as single line
607
631
  records = [data];
608
632
  }
@@ -686,7 +710,11 @@ async function enrichTransfers(result, apiInstance, chain) {
686
710
  const labelMap = {};
687
711
  for (const addr of addrs) {
688
712
  try {
689
- const labelsResult = await apiInstance.addressLabels({ address: addr, chain });
713
+ const labelsResult = await apiInstance.addressLabels({
714
+ address: addr,
715
+ chain,
716
+ requestOptions: { autoPaginate: false },
717
+ });
690
718
  labelMap[addr] = Array.isArray(labelsResult?.data)
691
719
  ? labelsResult.data.map(item => item.label)
692
720
  : labelsResult?.labels || [];
@@ -797,7 +825,11 @@ export async function batchProfile(api, params = {}) {
797
825
  }
798
826
  try {
799
827
  if (include.includes('labels')) {
800
- const labelsResult = await api.addressLabels({ address, chain });
828
+ const labelsResult = await api.addressLabels({
829
+ address,
830
+ chain,
831
+ requestOptions: { autoPaginate: false },
832
+ });
801
833
  entry.labels = Array.isArray(labelsResult?.data)
802
834
  ? labelsResult.data
803
835
  : labelsResult?.labels || [];
@@ -806,7 +838,11 @@ export async function batchProfile(api, params = {}) {
806
838
  entry.balance = await api.addressBalance({ address, chain });
807
839
  }
808
840
  if (include.includes('pnl')) {
809
- entry.pnl = await api.addressPnl({ address, chain });
841
+ entry.pnl = await api.addressPnl({
842
+ address,
843
+ chain,
844
+ requestOptions: { autoPaginate: false },
845
+ });
810
846
  }
811
847
  } catch (err) {
812
848
  entry.error = err.message;
@@ -817,19 +853,37 @@ export async function batchProfile(api, params = {}) {
817
853
  return { results, total: addresses.length, completed: results.filter(r => !r.error).length };
818
854
  }
819
855
 
820
- function normalizeTraceDepth(raw) {
856
+ function normalizeTraceDepth(raw, flags = {}) {
821
857
  const value = parseSafeIntegerOption(
822
858
  'depth',
823
859
  { depth: raw },
824
- {},
825
- 2,
860
+ flags,
826
861
  );
827
862
 
828
863
  return Math.max(1, Math.min(value, 5));
829
864
  }
830
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
+
831
885
  export async function traceCounterparties(api, params = {}) {
832
- 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;
833
887
  if (!address) {
834
888
  throw new NansenError('address is required for trace', ErrorCode.MISSING_PARAM);
835
889
  }
@@ -848,13 +902,15 @@ export async function traceCounterparties(api, params = {}) {
848
902
  if (!validation.valid) {
849
903
  throw new NansenError(validation.error, ErrorCode.INVALID_ADDRESS);
850
904
  }
851
- const clampedDepth = normalizeTraceDepth(depth);
905
+ const clampedDepth = normalizeTraceDepth(depth, depthFlags);
906
+ const clampedWidth = normalizeTraceWidth(width);
852
907
  const visited = new Set();
853
908
  const nodes = [];
854
909
  const edges = [];
855
910
  const queue = [{ addr: address, hop: 0 }];
856
911
  visited.add(address);
857
912
  nodes.push(address);
913
+ let truncated = false;
858
914
 
859
915
  while (queue.length > 0) {
860
916
  const { addr, hop } = queue.shift();
@@ -863,11 +919,12 @@ export async function traceCounterparties(api, params = {}) {
863
919
  try {
864
920
  const result = await api.addressCounterparties({
865
921
  address: addr, chain, days,
866
- pagination: { page: 1, per_page: width },
922
+ pagination: { page: 1, per_page: clampedWidth },
923
+ requestOptions: { autoPaginate: false },
867
924
  });
868
925
 
869
926
  const counterparties = result?.data?.results || result?.counterparties || result?.data || [];
870
- const items = Array.isArray(counterparties) ? counterparties.slice(0, width) : [];
927
+ const items = Array.isArray(counterparties) ? counterparties.slice(0, clampedWidth) : [];
871
928
 
872
929
  for (const cp of items) {
873
930
  const cpAddr = cp.counterparty_address || cp.address || cp.counterparty;
@@ -881,6 +938,11 @@ export async function traceCounterparties(api, params = {}) {
881
938
  });
882
939
 
883
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
+ }
884
946
  visited.add(cpAddr);
885
947
  nodes.push(cpAddr);
886
948
  queue.push({ addr: cpAddr, hop: hop + 1 });
@@ -894,9 +956,14 @@ export async function traceCounterparties(api, params = {}) {
894
956
  }
895
957
 
896
958
  return {
897
- root: address, chain, depth: clampedDepth,
959
+ root: address, chain, depth: clampedDepth, width: clampedWidth,
898
960
  nodes, edges,
899
- 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
+ },
900
967
  };
901
968
  }
902
969
 
@@ -918,8 +985,12 @@ export async function compareWallets(api, params = {}) {
918
985
  // error cannot masquerade as "no overlap" / "0 USD".
919
986
  const settle = (promise) => promise.then(value => ({ value }), error => ({ error }));
920
987
  const [cp1, cp2] = await Promise.all([
921
- settle(api.addressCounterparties({ address: addr1, chain, days })),
922
- settle(api.addressCounterparties({ address: addr2, chain, days })),
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
+ })),
923
994
  ]);
924
995
  await sleep(delayMs);
925
996
  const [bal1, bal2] = await Promise.all([
@@ -1028,19 +1099,38 @@ COMMANDS:
1028
1099
  alerts list, create, update, toggle, delete
1029
1100
  web search, fetch
1030
1101
  mcp install/uninstall/verify the Nansen MCP server
1031
- account Show API key status, plan, and remaining credits
1032
- auth status — offline auth status: key source, wallets (no network)
1033
- login Save API key (--human, NANSEN_API_KEY, or --api-key <key>)
1034
- 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
1035
1106
  doctor Diagnostics: auth, wallets, caches, connectivity (--offline --json)
1036
1107
  schema JSON schema for all commands (use "nansen schema <cmd>" for one)
1037
1108
  completion Shell completions: bash, zsh, fish
1038
- cache clear
1109
+ cache stats, clear
1039
1110
  changelog --since <version> to filter
1040
1111
 
1041
- 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
1042
1114
  FORMAT: --pretty --table --format csv --stream (NDJSON)
1043
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.
1044
1134
 
1045
1135
  TRADING:
1046
1136
  nansen trade quote --chain solana --from SOL --to USDC --amount 1000000000
@@ -1077,6 +1167,46 @@ Skills: npx skills add nansen-ai/nansen-cli (agent-optimised docs per command gr
1077
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
1078
1168
  `;
1079
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
+
1080
1210
  // Usage text for the `trade` command group. Shared by the trade handler and the
1081
1211
  // --help path in runCLI, so `nansen trade`, `nansen trade <sub> --help`, and the
1082
1212
  // deprecated top-level `quote`/`execute --help` all show the same usage.
@@ -1204,6 +1334,46 @@ export async function promptForConfirmation(question, { input = process.stdin, o
1204
1334
  });
1205
1335
  }
1206
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
+
1207
1377
  // Build command handlers (returns object with handler functions)
1208
1378
  export function buildCommands(deps = {}) {
1209
1379
  // Allow dependency injection for testing
@@ -1215,12 +1385,14 @@ export function buildCommands(deps = {}) {
1215
1385
  promptFn = prompt,
1216
1386
  confirmationPromptFn,
1217
1387
  log = console.log,
1218
- errorOutput: _errorOutput = console.error,
1388
+ errorOutput = console.error,
1219
1389
  NansenAPIClass: _NansenAPIClass = NansenAPI,
1220
- saveConfigFn = saveConfig,
1221
- deleteConfigFn = deleteConfig,
1390
+ authState = defaultAuthState(),
1391
+ browserLoginFn = browserLogin,
1222
1392
  getConfigFileFn = getConfigFile,
1223
- isTTY = process.stdin.isTTY,
1393
+ stdoutTTY = deps.isTTY ?? process.stdout.isTTY,
1394
+ stdinTTY = deps.isTTY ?? process.stdin.isTTY,
1395
+ stdin = process.stdin,
1224
1396
  env = process.env
1225
1397
  } = deps;
1226
1398
 
@@ -1333,29 +1505,25 @@ export function buildCommands(deps = {}) {
1333
1505
  },
1334
1506
 
1335
1507
  'login': async (args, apiInstance, flags, options) => {
1336
- if (flags.help || flags.h) {
1337
- log('nansen login - Save your Nansen API key\n');
1338
- log('USAGE:');
1339
- log(' nansen login --human (interactive prompt; key never enters shell history)');
1340
- log(' nansen login (uses NANSEN_API_KEY when already set)');
1341
- log(' nansen login --api-key <key> (literal key IS recorded in shell history)\n');
1342
- log('OPTIONS:');
1343
- log(' --api-key <key> Your Nansen API key (recorded in shell history — prefer --human)');
1344
- log(' --human Enable interactive prompt');
1345
- log(' --help Show this help\n');
1346
- log('Setting a literal key in a command may record it in shell history.');
1347
- log('Get your API key at: https://app.nansen.ai/auth/agent-setup');
1348
- 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');
1349
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'];
1350
1520
 
1351
- let apiKey = options['api-key'];
1352
-
1353
- if (!apiKey) {
1354
- apiKey = process.env.NANSEN_API_KEY;
1521
+ if (apiKey === undefined) {
1522
+ apiKey = env.NANSEN_API_KEY?.trim() || undefined;
1355
1523
  }
1356
1524
 
1357
- if (!apiKey && flags.human) {
1358
- if (!isTTY) {
1525
+ if (apiKey === undefined && flags.human) {
1526
+ if (!stdinTTY) {
1359
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', {
1360
1528
  error: 'NOT_A_TTY',
1361
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).',
@@ -1378,73 +1546,84 @@ export function buildCommands(deps = {}) {
1378
1546
  });
1379
1547
  }
1380
1548
 
1381
- // Verify API key before saving
1382
- const NansenAPIClass = _NansenAPIClass;
1383
- const testApi = new NansenAPIClass(apiKey.trim(), undefined, {
1384
- retry: { maxRetries: 2 },
1385
- cache: { enabled: false }
1386
- });
1387
-
1388
1549
  let accountInfo;
1550
+ let cleanup;
1551
+ const baseUrl = authConfigView(env).baseUrl;
1552
+ const attempt = await authState.begin({ preflight: false });
1389
1553
  try {
1390
- accountInfo = await testApi.getAccount();
1391
- } catch (error) {
1392
- if (error.code === ErrorCode.UNAUTHORIZED) {
1393
- throw new CommandError('The API key is not valid.', 'INVALID_API_KEY', {
1394
- error: 'INVALID_API_KEY',
1395
- message: 'The API key is not valid.',
1396
- 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,
1397
1592
  });
1398
1593
  }
1399
- // Restore signal from the STRUCTURED error code only — never from
1400
- // error.message, which can echo the upstream response body (and the key
1401
- // with it). A transient failure shouldn't read as "check your key".
1402
- let message = 'Could not verify API key.';
1403
- let resolution = ['Check your internet connection', 'Try again'];
1404
- if (error.code === ErrorCode.RATE_LIMITED) {
1405
- message = 'Rate limited while verifying the API key.';
1406
- resolution = ['Wait a moment, then run nansen login again'];
1407
- } else if (error.code === ErrorCode.SERVER_ERROR || error.code === ErrorCode.SERVICE_UNAVAILABLE) {
1408
- message = 'The Nansen API is unavailable right now, so the key could not be verified.';
1409
- resolution = ['Try again shortly'];
1410
- } else if (error.code === ErrorCode.TIMEOUT) {
1411
- message = 'Timed out verifying the API key.';
1412
- resolution = ['Check your connection', 'Try again'];
1413
- }
1414
- throw new CommandError(message, 'VERIFICATION_FAILED', {
1415
- error: 'VERIFICATION_FAILED',
1416
- message,
1417
- resolution,
1418
- });
1419
- }
1420
1594
 
1421
- // Key is valid - now save
1422
- saveConfigFn({
1423
- apiKey: apiKey.trim(),
1424
- baseUrl: 'https://api.nansen.ai'
1425
- });
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.');
1426
1607
 
1427
1608
  log(`✓ Saved to ${getConfigFileFn()}\n`);
1428
- 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) {
1429
1612
  log(`Plan: ${accountInfo.plan}`);
1430
1613
  }
1431
- if (accountInfo?.credits_remaining !== undefined) {
1614
+ if (!fromStdin && accountInfo?.credits_remaining !== undefined) {
1432
1615
  log(`Credits remaining: ${accountInfo.credits_remaining}`);
1433
1616
  }
1434
- 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:');
1435
1618
  log(' nansen research token screener --chain solana --pretty');
1436
1619
  },
1437
1620
 
1438
1621
  'logout': async (_args, _apiInstance, _flags, _options) => {
1439
- const deleted = deleteConfigFn();
1440
- if (deleted) {
1441
- log(`✓ Removed ${getConfigFileFn()}`);
1442
- } else {
1443
- log('No saved credentials found');
1444
- }
1445
- if (env.NANSEN_API_KEY) {
1446
- log('Warning: NANSEN_API_KEY remains active. Run: unset NANSEN_API_KEY');
1447
- }
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');
1448
1627
  },
1449
1628
 
1450
1629
  'help': async (_args, _apiInstance, _flags, _options) => {
@@ -1522,32 +1701,44 @@ export function buildCommands(deps = {}) {
1522
1701
  return compactSchema(SCHEMA);
1523
1702
  },
1524
1703
 
1525
- 'cache': async (args, _apiInstance, _flags, _options) => {
1526
- const subcommand = args[0] || 'help';
1527
-
1704
+ 'cache': async (args, _apiInstance, flags, options) => {
1705
+ const subcommand = args[0] ?? 'help';
1706
+
1528
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
+ },
1529
1716
  'clear': () => {
1530
- const count = clearCache();
1531
- log(`✓ Cleared ${count} cached responses`);
1532
- 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)));
1533
1722
  },
1534
1723
  'help': () => {
1535
- log('Cache Management\n');
1536
- log('USAGE:');
1537
- log(' nansen cache clear Clear all cached responses\n');
1538
- log('CACHE OPTIONS (for any command):');
1539
- log(' --cache Enable caching for this session');
1540
- log(' --no-cache Bypass cache for this request');
1541
- log(' --cache-ttl <seconds> Set non-negative safe integer cache TTL (default: 300)');
1724
+ log(CACHE_HELP);
1542
1725
  }
1543
1726
  };
1544
-
1545
- if (!handlers[subcommand]) {
1546
- log(`Unknown cache subcommand: ${subcommand}`);
1547
- handlers['help']();
1548
- 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
+ );
1549
1741
  }
1550
-
1551
1742
  return handlers[subcommand]();
1552
1743
  },
1553
1744
 
@@ -1680,16 +1871,10 @@ export function buildCommands(deps = {}) {
1680
1871
  'trace': () => {
1681
1872
  rejectBlankOption(options.delay, 'delay', '1000');
1682
1873
  rejectBlankOption(options.depth, 'depth', '2');
1683
- if (flags.depth) {
1684
- throw new NansenError(
1685
- '--depth requires a safe integer value',
1686
- ErrorCode.INVALID_PARAMS,
1687
- );
1688
- }
1689
- const depth = options.depth ?? 2;
1874
+ const depth = options.depth;
1690
1875
  const width = parseNonNegativeSafeIntegerOption('width', options, flags, 10);
1691
1876
  const delayMs = parseNonNegativeSafeIntegerOption('delay', options, flags, 1000);
1692
- return traceCounterparties(apiInstance, { address, chain, depth, width, days, delayMs });
1877
+ return traceCounterparties(apiInstance, { address, chain, depth, depthFlags: flags, width, days, delayMs });
1693
1878
  },
1694
1879
  'compare': () => {
1695
1880
  const addrs = parseAddressList(options.addresses);
@@ -1767,24 +1952,57 @@ export function buildCommands(deps = {}) {
1767
1952
  // candidate fetch has to cover every page up to the requested one.
1768
1953
  const requestedLimit = pagination?.per_page || 100;
1769
1954
  const requestedPage = pagination?.page || 1;
1955
+ const paginateAll = flags.paginate || flags.all;
1770
1956
  const searchPagination = search
1771
- ? { page: 1, per_page: Math.max(500, requestedPage * requestedLimit) }
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
+ }
1772
1968
  : pagination;
1773
1969
  const result = await apiInstance.tokenScreener({ chains, timeframe, filters, orderBy, pagination: searchPagination });
1774
1970
  if (search) {
1775
1971
  const q = search.toLowerCase();
1776
1972
  const offset = (requestedPage - 1) * requestedLimit;
1777
- const filterArr = (arr) => arr.filter(t =>
1778
- (t.token_symbol && t.token_symbol.toLowerCase().includes(q)) ||
1779
- (t.token_name && t.token_name.toLowerCase().includes(q)) ||
1780
- (t.token_address && t.token_address.toLowerCase() === q)
1781
- ).slice(offset, offset + requestedLimit);
1782
1973
  // Handle nested response shapes: {data: [...]} or {data: {data: [...]}}
1974
+ let candidates;
1975
+ let rebuild;
1783
1976
  if (Array.isArray(result?.data)) {
1784
- return { ...result, data: filterArr(result.data) };
1785
- } else if (result?.data?.data && Array.isArray(result.data.data)) {
1786
- 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;
1787
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;
1788
2006
  }
1789
2007
  return result;
1790
2008
  },
@@ -1867,7 +2085,17 @@ export function buildCommands(deps = {}) {
1867
2085
 
1868
2086
  // Enrich transfers with Nansen labels for from/to addresses
1869
2087
  if (subcommand === 'transfers' && (options.enrich || flags.enrich)) {
1870
- 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
+ }
1871
2099
  }
1872
2100
 
1873
2101
  return result;
@@ -2240,6 +2468,31 @@ export function generateSubcommandHelp(command, subcommand, prefix = null) {
2240
2468
  return lines.join('\n');
2241
2469
  }
2242
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
+
2243
2496
  // Run CLI with given args (returns result, allows custom output/exit handlers)
2244
2497
  export async function runCLI(rawArgs, deps = {}) {
2245
2498
  const {
@@ -2251,6 +2504,7 @@ export async function runCLI(rawArgs, deps = {}) {
2251
2504
  // Output TTY controls human-vs-structured error rendering. Keep the
2252
2505
  // existing `isTTY` seam for callers/tests that inject both terminal states.
2253
2506
  isTTY = process.stdout.isTTY,
2507
+ env = process.env,
2254
2508
  } = deps;
2255
2509
 
2256
2510
  // Command-layer interactivity is intentionally governed by stdin. Besides
@@ -2268,6 +2522,8 @@ export async function runCLI(rawArgs, deps = {}) {
2268
2522
  const inputInteractiveDeps = {
2269
2523
  ...deps,
2270
2524
  isTTY: isInputTTY,
2525
+ stdoutTTY: isTTY,
2526
+ stdinTTY: isInputTTY,
2271
2527
  promptFn: deps.promptFn ?? prompt,
2272
2528
  confirmationPromptFn: deps.confirmationPromptFn ?? promptForConfirmation,
2273
2529
  confirmationLog: deps.confirmationLog ?? errorOutput,
@@ -2278,6 +2534,13 @@ export async function runCLI(rawArgs, deps = {}) {
2278
2534
  };
2279
2535
 
2280
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
+ };
2281
2544
  try {
2282
2545
  parsed = parseArgs(rawArgs);
2283
2546
  } catch (error) {
@@ -2294,27 +2557,34 @@ export async function runCLI(rawArgs, deps = {}) {
2294
2557
  const subArgs = positional.slice(1);
2295
2558
  const subcommand = subArgs[0];
2296
2559
 
2297
-
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);
2298
2564
 
2299
2565
  const pretty = flags.pretty || flags.p;
2300
2566
  const table = flags.table || flags.t;
2301
2567
  const stream = flags.stream || flags.s;
2302
2568
  const csv = options.format === 'csv';
2303
2569
 
2304
- // `auth` and `doctor --offline` promise zero network activity — that
2305
- // contract covers the background update-check fetch and telemetry too,
2306
- // 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.
2307
2574
  const isMcpUsage = command === 'mcp' && (subcommand !== 'verify' || flags.help || flags.h);
2308
- // `completion` renders from the checked-in schema — no network, and its
2309
- // stdout is piped straight into a shell, so keep the update check out of it.
2310
- const isOfflineCommand = command === 'auth' || (command === 'doctor' && flags.offline) || isMcpUsage || command === 'completion';
2311
- const trackSucceeded = isOfflineCommand ? async () => {} : trackCommandSucceeded;
2312
- 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;
2313
2583
 
2314
2584
  // Update check (read cached result + schedule background refresh)
2315
- const updateNotification = getUpdateNotification(VERSION);
2316
- const upgradeNotice = getUpgradeNotice(VERSION);
2317
- if (!isOfflineCommand) scheduleUpdateCheck();
2585
+ const updateNotification = isOfflineCommand ? null : getUpdateNotification(VERSION);
2586
+ const upgradeNotice = isOfflineCommand ? null : getUpgradeNotice(VERSION);
2587
+ if (!isOfflineCommand && !isAuthMutation) scheduleUpdateCheck();
2318
2588
  const notify = () => {
2319
2589
  if (upgradeNotice) errorOutput(upgradeNotice);
2320
2590
  if (updateNotification) errorOutput(updateNotification);
@@ -2343,7 +2613,7 @@ export async function runCLI(rawArgs, deps = {}) {
2343
2613
  if (command === 'help' || flags.help || flags.h) {
2344
2614
  // Help for an offline command still owes the zero-network contract: the
2345
2615
  // cost-map refresh fetches the OpenAPI spec and writes ~/.nansen/cost-map.json.
2346
- if (!isOfflineCommand) await refreshCostMapIfStale();
2616
+ if (!isOfflineCommand && !isAuthMutation) await refreshCostMapIfStale();
2347
2617
  // Check for subcommand-specific help: nansen <command> <subcommand> --help
2348
2618
  if (flags.help || flags.h) {
2349
2619
  // Handle 'research <category> <sub> --help' (3-level)
@@ -2396,8 +2666,8 @@ export async function runCLI(rawArgs, deps = {}) {
2396
2666
  }
2397
2667
  }
2398
2668
  // Then try command-level help (list subcommands)
2399
- // Skip for 'trade'/'alerts' — let the handler show its own usage
2400
- 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]);
2401
2671
  if (command && cmdSchemaLookup) {
2402
2672
  const cmdSchema = cmdSchemaLookup;
2403
2673
  const lines = [`${command} — ${cmdSchema.description}`];
@@ -2427,9 +2697,8 @@ export async function runCLI(rawArgs, deps = {}) {
2427
2697
  // Prevents destructive commands like logout from running when user just wants help
2428
2698
  if (commands[command]) {
2429
2699
  const simpleHelp = {
2430
- 'logout': 'nansen logout — Remove saved API key from ~/.nansen/config.json',
2431
2700
  'schema': 'nansen schema [command] [--pretty] — Show JSON schema for all commands (or a specific command)',
2432
- 'cache': 'nansen cache clear — Clear the API response cache',
2701
+ 'cache': CACHE_HELP,
2433
2702
  };
2434
2703
  if (simpleHelp[command]) {
2435
2704
  output(simpleHelp[command]);
@@ -2491,7 +2760,10 @@ export async function runCLI(rawArgs, deps = {}) {
2491
2760
  // Configure cache options
2492
2761
  const cacheTtl = parseNonNegativeSafeIntegerOption('cache-ttl', options, flags, 300);
2493
2762
  const cacheOptions = {
2494
- 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',
2495
2767
  ttl: cacheTtl
2496
2768
  };
2497
2769
 
@@ -2499,7 +2771,16 @@ export async function runCLI(rawArgs, deps = {}) {
2499
2771
  if (options['x402-payment-signature']) {
2500
2772
  defaultHeaders['Payment-Signature'] = options['x402-payment-signature'];
2501
2773
  }
2502
- 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
+ }
2503
2784
 
2504
2785
  // Deprecated top-level aliases otherwise run silently (the notice was only
2505
2786
  // shown in --help). Warn on stderr so it doesn't pollute parsed stdout.
@@ -2528,18 +2809,7 @@ export async function runCLI(rawArgs, deps = {}) {
2528
2809
  // stderr so it never contaminates the JSON on stdout that agents parse.
2529
2810
  // Placed before every return path below so it fires for operational
2530
2811
  // commands too, which print their own output and return undefined.
2531
- const lowCredits = creditWarning(api.lastResponseMeta);
2532
- if (lowCredits) errorOutput(lowCredits);
2533
- for (const notice of noticeWarnings(api.lastResponseMeta)) errorOutput(notice);
2534
-
2535
- // What this call cost — authoritative header when the API sent one, else
2536
- // the cached spec estimate. stderr only, so stdout JSON stays pure.
2537
- const charged = creditsCharged(api.lastResponseMeta, api.lastEndpoint);
2538
- if (charged?.source === 'header') {
2539
- errorOutput(`Credits: ${charged.cost} (this call)`);
2540
- } else if (charged?.source === 'estimate') {
2541
- errorOutput(`Credits: ~${charged.estimate.free} free / ${charged.estimate.pro} pro (estimated)`);
2542
- }
2812
+ emitResponseMetadataOnce();
2543
2813
 
2544
2814
  // Commands that handle their own output return undefined
2545
2815
  if (result === undefined) {
@@ -2585,6 +2855,9 @@ export async function runCLI(rawArgs, deps = {}) {
2585
2855
  await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
2586
2856
  return { type: csv ? 'csv' : 'success', data: result };
2587
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();
2588
2861
  // Unified error envelope across all command families (perp/bridge/trade):
2589
2862
  // every failure serializes through formatError as
2590
2863
  // {success:false, error, code, status, details}. A CommandError's structured