nansen-cli 2.2.0 → 2.4.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 (78) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +109 -33
  3. package/docs/auth.md +56 -0
  4. package/docs/browser-login.md +101 -7
  5. package/docs/error-codes.md +249 -0
  6. package/package.json +10 -4
  7. package/skills/nansen-agent-guide/SKILL.md +54 -1
  8. package/skills/nansen-alerts-webhook-listener/SKILL.md +1 -1
  9. package/skills/nansen-dca-tracker/SKILL.md +1 -1
  10. package/skills/nansen-defi-positions/SKILL.md +1 -1
  11. package/skills/nansen-exit-signals/SKILL.md +2 -2
  12. package/skills/nansen-fund-tracker/SKILL.md +1 -1
  13. package/skills/nansen-general-search/SKILL.md +1 -1
  14. package/skills/nansen-holder-analysis/SKILL.md +2 -2
  15. package/skills/nansen-limit-orders/SKILL.md +1 -1
  16. package/skills/nansen-mpp-payment/SKILL.md +2 -2
  17. package/skills/nansen-perp-screener/SKILL.md +1 -1
  18. package/skills/nansen-perp-trader-profile/SKILL.md +1 -1
  19. package/skills/nansen-polymarket-deep-dive/SKILL.md +1 -1
  20. package/skills/nansen-polymarket-insider-scan/SKILL.md +1 -1
  21. package/skills/nansen-polymarket-trader-profile/SKILL.md +1 -1
  22. package/skills/nansen-portfolio-tracker/SKILL.md +1 -1
  23. package/skills/nansen-prediction-markets/SKILL.md +1 -1
  24. package/skills/nansen-sm-cross-chain-flows/SKILL.md +1 -1
  25. package/skills/nansen-smart-alerts/SKILL.md +2 -1
  26. package/skills/nansen-smart-money-alpha/SKILL.md +1 -1
  27. package/skills/nansen-smart-money-tracker/SKILL.md +8 -7
  28. package/skills/nansen-smart-money-trend/SKILL.md +1 -1
  29. package/skills/nansen-token-research/SKILL.md +1 -1
  30. package/skills/nansen-token-screener/SKILL.md +1 -1
  31. package/skills/nansen-token-transfer-analysis/SKILL.md +1 -1
  32. package/skills/nansen-trading/SKILL.md +1 -1
  33. package/skills/nansen-wallet-batch/SKILL.md +1 -1
  34. package/skills/nansen-wallet-clustering/SKILL.md +1 -1
  35. package/skills/nansen-wallet-deep-dive/SKILL.md +1 -1
  36. package/skills/nansen-wallet-keychain-migration/SKILL.md +1 -1
  37. package/skills/nansen-wallet-manager/SKILL.md +1 -1
  38. package/skills/nansen-wallet-profiler/SKILL.md +1 -1
  39. package/skills/nansen-web-fetcher/SKILL.md +1 -1
  40. package/skills/nansen-web-searcher/SKILL.md +1 -1
  41. package/src/api-endpoints.json +1605 -0
  42. package/src/api.js +336 -121
  43. package/src/auth-credentials.js +1 -0
  44. package/src/auth-state.js +2 -2
  45. package/src/auth-store-native.js +6 -1
  46. package/src/auth-store-worker.js +1 -1
  47. package/src/auth-store.js +9 -4
  48. package/src/bridge.js +19 -10
  49. package/src/cli.js +258 -107
  50. package/src/commands/agent.js +2 -3
  51. package/src/commands/alerts.js +277 -9
  52. package/src/commands/completion.js +6 -1
  53. package/src/commands/feedback.js +413 -0
  54. package/src/commands/mcp.js +1 -1
  55. package/src/commands/research.js +14 -37
  56. package/src/cost-cache.js +33 -7
  57. package/src/doctor.js +14 -5
  58. package/src/error-codes.js +226 -0
  59. package/src/feedback-journal.js +86 -0
  60. package/src/input-validation.js +551 -0
  61. package/src/limit-order.js +12 -3
  62. package/src/perp.js +2 -1
  63. package/src/privy.js +144 -48
  64. package/src/query-options.js +30 -7
  65. package/src/rpc-urls.js +3 -1
  66. package/src/schema.json +1254 -150
  67. package/src/solana-tx.js +4 -0
  68. package/src/telemetry.js +5 -1
  69. package/src/trade-validation.js +190 -21
  70. package/src/trading.js +229 -129
  71. package/src/transfer.js +7 -1
  72. package/src/update-check.js +32 -5
  73. package/src/wallet.js +220 -57
  74. package/src/walletconnect-x402.js +152 -52
  75. package/src/x402-audit.js +191 -0
  76. package/src/x402-payment-balance.js +90 -0
  77. package/src/x402-policy.js +151 -4
  78. package/src/x402.js +51 -22
package/src/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- import { authConfigView } from './auth-credentials.js';
1
+ import { authConfigView, ENV_API_KEY_GUIDANCE } from './auth-credentials.js';
2
2
  import { browserLogin, defaultAuthState, cleanupMessage } from './auth-login.js';
3
3
  import { readApiKeyInput } from './auth-key-input.js';
4
4
  /**
@@ -13,11 +13,13 @@ import { buildPerpCommands } from './perp.js';
13
13
  import { buildTradingCommands } from './trading.js';
14
14
  import { buildLimitOrderCommands } from './limit-order.js';
15
15
  import { formatAlertsTable, buildAlertsCommands } from './commands/alerts.js';
16
+ import { buildFeedbackCommands, feedbackErrorText } from './commands/feedback.js';
16
17
  import { buildAgentCommands } from './commands/agent.js';
17
18
  import { buildMcpCommands } from './commands/mcp.js';
18
19
  import { buildCompletionCommands } from './commands/completion.js';
19
20
  import { buildResearchCommands, RESEARCH_HISTORICAL_SUBCOMMANDS, RESEARCH_SUBCOMMANDS } from './commands/research.js';
20
- import { buildPagination, parseSort, parseCsvOption, rejectBlankOption, parseObjectOption } from './query-options.js';
21
+ import { buildPagination, parseSort, parseCsvOption, rejectBlankOption, parseFiltersOption } from './query-options.js';
22
+ import { resolveResearchCommand, validateResearchInput, validateOutputOptions, validateFieldSelection, unknownCommandError, normalizeFilterAddresses } from './input-validation.js';
21
23
  import { enableAutoPagination, DEFAULT_MAX_PAGES, MAX_PAGES_LIMIT, locateRows } from './auto-paginate.js';
22
24
  export { buildPagination, parseSort };
23
25
  import { resolveAddress, isEnsName } from './ens.js';
@@ -25,7 +27,7 @@ import { compareSemver } from './semver.js';
25
27
  import fs from 'fs';
26
28
  import { getUpdateNotification, getUpgradeNotice, scheduleUpdateCheck } from './update-check.js';
27
29
  import { getAuthStatus, runDoctorChecks, runConnectivityChecks, formatDoctorReport } from './doctor.js';
28
- import { refreshCostMapIfStale, getCostForEndpoint, creditsCharged } from './cost-cache.js';
30
+ import { refreshCostMapIfStale, getCostForEndpoint, getCostVariants, formatCost, creditsCharged } from './cost-cache.js';
29
31
  import { collectCacheStats, clearCaches, formatCacheStats, formatCacheClear } from './cache-inspect.js';
30
32
  import { creditWarning, noticeWarnings } from './response-meta.js';
31
33
  import { trackCommandSucceeded, trackCommandFailed, trackAuthCommand } from './telemetry.js';
@@ -39,11 +41,31 @@ const { version: VERSION, engines: ENGINES } = require('../package.json');
39
41
  // ============= Schema Definition =============
40
42
 
41
43
  const schemaDefinition = require('./schema.json');
44
+ // Chains and request fields per API endpoint, vendored from the public
45
+ // OpenAPI spec by scripts/sync-api-endpoints.js (npm run endpoints:sync).
46
+ export const API_ENDPOINTS = require('./api-endpoints.json').endpoints;
47
+
48
+ /**
49
+ * Add `supportedChains` to every command whose --chain/--chains the API
50
+ * restricts, so `nansen schema` documents the list the CLI enforces. An
51
+ * option with its own `enum` already documents it.
52
+ */
53
+ function withSupportedChains(definition, endpoints) {
54
+ const copy = structuredClone(definition);
55
+ (function walk(node) {
56
+ if (!node || typeof node !== 'object') return;
57
+ const chainOption = node.options?.chain ?? node.options?.chains;
58
+ const chains = endpoints[node.endpoint]?.chains;
59
+ if (chainOption && !chainOption.enum && chains?.length) node.supportedChains = chains;
60
+ for (const child of Object.values(node.subcommands || {})) walk(child);
61
+ })(copy.commands.research);
62
+ return copy;
63
+ }
42
64
 
43
65
  // SCHEMA is the static definition with version injected at runtime.
44
66
  // The schema.json file is the source of truth for command metadata (returns, options, etc.)
45
67
  // and should be updated whenever the API changes — do not edit returns arrays here.
46
- export const SCHEMA = { version: VERSION, ...schemaDefinition };
68
+ export const SCHEMA = { version: VERSION, ...withSupportedChains(schemaDefinition, API_ENDPOINTS) };
47
69
 
48
70
  // ============= Pagination =============
49
71
 
@@ -197,12 +219,15 @@ export function compactSchema(schema) {
197
219
  // Long options that never consume the next argument. The shell-completion
198
220
  // generator needs the same list to tell an option's value apart from a
199
221
  // subcommand, so it lives here rather than inline in parseArgs.
222
+ // `gasless` is retained after the flag's removal: trade execute rejects it
223
+ // explicitly, and that rejection only fires if it still parses as a boolean
224
+ // rather than swallowing the token after it.
200
225
  export const VALUELESS_FLAGS = new Set([
201
226
  'pretty', 'help', 'version', 'table', 'no-retry', 'cache', 'no-cache', 'stream',
202
227
  'enrich', 'full', 'human', 'no-browser', 'api-key-stdin', 'enabled', 'disabled', 'expert', 'json', 'offline',
203
228
  'no-simulate', 'no-verify-outcome', 'no-revoke-excessive-allowance', 'dry-run',
204
229
  'send-api-key', 'all', 'max', 'gasless', 'auto-slippage', 'unsafe-no-password',
205
- 'reveal', 'yes', 'paginate', 'debug',
230
+ 'reveal', 'yes', 'paginate', 'debug', 'new',
206
231
  ]);
207
232
 
208
233
  export function parseArgs(args) {
@@ -456,15 +481,55 @@ export function formatValue(val) {
456
481
  return String(val);
457
482
  }
458
483
 
484
+ // A row of the perp-positions payload: the wrapper plus its nested `position`.
485
+ // `position` may be absent because --fields runs before formatting and can
486
+ // strip it, so a wrapper-only entry is still a row. Anything else in that key
487
+ // means the payload is not the perp shape and belongs in the JSON fallback.
488
+ function isPositionEntry(entry) {
489
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return false;
490
+ const { position } = entry;
491
+ return position === undefined
492
+ || (position !== null && typeof position === 'object' && !Array.isArray(position));
493
+ }
494
+
495
+ // Perp positions wrap each row in `position`. Flatten only for tabular
496
+ // presentation so JSON output retains the API payload and account summaries.
497
+ function locateTabularRows(data) {
498
+ let sawPositions = false;
499
+ if (data?.success !== false) {
500
+ for (const payload of [data, data?.data, data?.data?.data]) {
501
+ const positions = payload?.asset_positions;
502
+ if (!Array.isArray(positions)) continue;
503
+ sawPositions = true;
504
+ const rows = positions.every(isPositionEntry)
505
+ ? positions.map(({ position, ...fields }) => ({ ...position, ...fields }))
506
+ : null;
507
+ // A row with no fields renders as a blank line, which tells the reader
508
+ // less than the JSON fallback does. Treat it as "not the perp shape".
509
+ if (rows && rows.every(row => Object.keys(row).length > 0)) return { rows };
510
+ }
511
+ }
512
+ // An `asset_positions` array that does not hold perp rows is malformed, not
513
+ // a descriptive row array that happens to share the name. Reading it as one
514
+ // would drop the wrapper and surface the broken rows as columns, so leave it
515
+ // to the payload fallback.
516
+ return sawPositions ? null : locateRows(data, { descriptive: true });
517
+ }
518
+
519
+ // Records for the tabular formatters: the located rows, or the payload itself
520
+ // when nothing matched. Rows that carry no fields at all would render as blank
521
+ // lines, which says less than the payload does, so they take that same
522
+ // fallback. An empty row set is left alone — it means "no results".
523
+ function tabularRecords(data) {
524
+ if (typeof data !== 'object' || data === null) return [];
525
+ const rows = locateTabularRows(data)?.rows;
526
+ if (rows && (rows.length === 0 || rows.some(row => Object.keys(row).length > 0))) return rows;
527
+ return [Array.isArray(data) ? { data } : data];
528
+ }
529
+
459
530
  // Table formatter for human-readable output
460
531
  export function formatTable(data) {
461
- // Extract array of records from various response shapes
462
- const located = locateRows(data, { descriptive: true });
463
- let records = located?.rows || [];
464
- if (!located && typeof data === 'object' && data !== null) {
465
- // Single object - convert to array
466
- records = [Array.isArray(data) ? { data } : data];
467
- }
532
+ const records = tabularRecords(data);
468
533
 
469
534
  if (records.length === 0) {
470
535
  return 'No data';
@@ -523,12 +588,7 @@ export function formatTable(data) {
523
588
  * Format data as CSV with header row
524
589
  */
525
590
  export function formatCsv(data) {
526
- // Extract array of records from various response shapes
527
- const located = locateRows(data, { descriptive: true });
528
- let records = located?.rows || [];
529
- if (!located && typeof data === 'object' && data !== null) {
530
- records = [Array.isArray(data) ? { data } : data];
531
- }
591
+ const records = tabularRecords(data);
532
592
 
533
593
  if (records.length === 0) return '';
534
594
 
@@ -743,7 +803,8 @@ async function enrichTransfers(result, apiInstance, chain) {
743
803
  */
744
804
  export function parseAddressList(raw) {
745
805
  if (Array.isArray(raw)) {
746
- return raw.map(a => String(a).trim()).filter(Boolean);
806
+ // A repeated flag may carry a list itself (`--addresses a,b --addresses c`).
807
+ return raw.flatMap(a => String(a).split(',')).map(a => a.trim()).filter(Boolean);
747
808
  }
748
809
  if (!raw) return [];
749
810
 
@@ -1097,6 +1158,7 @@ COMMANDS:
1097
1158
  wallet ${WALLET_SUBCOMMANDS.join(', ')}
1098
1159
  agent Ask the Nansen AI research agent (fast/expert modes)
1099
1160
  alerts list, create, update, toggle, delete
1161
+ feedback preferences, submit, resume, forget local data, or get a receipt (--json for structured output)
1100
1162
  web search, fetch
1101
1163
  mcp install/uninstall/verify the Nansen MCP server
1102
1164
  account Check the effective credential, plan, and remaining credits (free)
@@ -1143,7 +1205,7 @@ BRIDGE (Hyperliquid):
1143
1205
  nansen bridge quote --from-chain base --to-chain hyperliquid --from-token USDC --amount 1000000
1144
1206
  nansen bridge execute --quote <quoteId>
1145
1207
  nansen bridge status --request-id <id>
1146
- Supports EVM chains (ethereum, base, arbitrum, polygon, bnb) <-> Hyperliquid.
1208
+ Supported routes: ${formatBridgeRoutes()}
1147
1209
 
1148
1210
  EXAMPLES:
1149
1211
  nansen trade quote --chain base --from ETH --to USDC --amount 1000000000000000000
@@ -1158,8 +1220,8 @@ DEPRECATED ALIASES (still work, will be removed in a future version):
1158
1220
 
1159
1221
  Research chains: ${SCHEMA.chains.join(', ')}
1160
1222
  Trade chains: solana, base
1161
- Bridge chains: ethereum, base, arbitrum, polygon, bnb, hyperliquid
1162
- Labels: Fund, Smart Trader, 30D/90D/180D Smart Trader, Smart HL Perps Trader
1223
+ Bridge routes: ${formatBridgeRoutes()}
1224
+ Labels: Smart Trader, 30D/90D/180D Smart Trader, Smart HL Perps Trader (Smart Trader covers all windows; Fund is no longer a Smart Money label)
1163
1225
 
1164
1226
  Docs: https://docs.nansen.ai
1165
1227
  Skills: npx skills add nansen-ai/nansen-cli (agent-optimised docs per command group)
@@ -1188,7 +1250,7 @@ WHAT CACHES:
1188
1250
  written to the response cache — that is all of "nansen research ...", plus
1189
1251
  "alerts list" and "alerts get".
1190
1252
  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.
1253
+ agent (streamed), feedback, every trade, bridge, wallet and mcp command, and perp trading.
1192
1254
  The analytics commands "perp screener" and "perp leaderboard" are cached.
1193
1255
 
1194
1256
  CACHE OPTIONS (for any command):
@@ -1207,9 +1269,7 @@ expire on their own, and an unexecuted quote is still spendable. Credentials,
1207
1269
  wallets and config are never changed by this command. CLI startup loads the saved
1208
1270
  config as usual.`;
1209
1271
 
1210
- // Usage text for the `trade` command group. Shared by the trade handler and the
1211
- // --help path in runCLI, so `nansen trade`, `nansen trade <sub> --help`, and the
1212
- // deprecated top-level `quote`/`execute --help` all show the same usage.
1272
+ // Overview for the trade group. Individual subcommand help comes from the schema.
1213
1273
  export const TRADE_USAGE = `nansen trade — DEX trading commands
1214
1274
 
1215
1275
  SUBCOMMANDS:
@@ -1404,7 +1464,7 @@ export function buildCommands(deps = {}) {
1404
1464
  'auth': async (args, _apiInstance, _flags, _options) => {
1405
1465
  const subcommand = args[0] || 'status';
1406
1466
  if (subcommand !== 'status') {
1407
- throw new NansenError(`Unknown auth subcommand: ${subcommand}. Available: status`, ErrorCode.UNKNOWN);
1467
+ throw unknownCommandError('auth subcommand', subcommand, ['status']);
1408
1468
  }
1409
1469
  return getAuthStatus();
1410
1470
  },
@@ -1497,8 +1557,8 @@ export function buildCommands(deps = {}) {
1497
1557
  }),
1498
1558
  };
1499
1559
 
1500
- if (!handlers[subcommand]) {
1501
- throw new NansenError(`Unknown web subcommand: ${subcommand}. Available: search, fetch`, ErrorCode.UNKNOWN);
1560
+ if (!Object.hasOwn(handlers, subcommand)) {
1561
+ throw unknownCommandError('web subcommand', subcommand, ['search', 'fetch']);
1502
1562
  }
1503
1563
 
1504
1564
  return handlers[subcommand]();
@@ -1514,7 +1574,7 @@ export function buildCommands(deps = {}) {
1514
1574
  if ('api-key' in options && typeof options['api-key'] !== 'string') throw new CommandError('--api-key must be a single key string.', 'INVALID_PARAMS');
1515
1575
  if (!fromStdin && !flags.human && options['api-key'] === undefined) {
1516
1576
  if (!stdinTTY || !stdoutTTY) {
1517
- throw new CommandError('Browser login requires an interactive terminal. In a headless environment, set NANSEN_API_KEY and run nansen login --human, or pipe a key to nansen login --api-key-stdin.', 'NOT_A_TTY');
1577
+ throw new CommandError(`Browser login requires an interactive terminal. ${ENV_API_KEY_GUIDANCE} To deliberately save an API key instead, use nansen login --human or nansen login --api-key-stdin. Saving requires native authentication locking.`, 'NOT_A_TTY');
1518
1578
  }
1519
1579
  return browserLoginFn({ flags, env, isTTY: stdoutTTY, log, errorOutput, state: authState });
1520
1580
  }
@@ -1578,7 +1638,10 @@ export function buildCommands(deps = {}) {
1578
1638
  // with it). A transient failure shouldn't read as "check your key".
1579
1639
  let message = 'Could not verify API key.';
1580
1640
  let resolution = ['Check your internet connection', 'Try again'];
1581
- if (error.code === ErrorCode.RATE_LIMITED) {
1641
+ if (error.code === ErrorCode.NETWORK_ERROR) {
1642
+ message = 'Could not reach the Nansen API to verify the API key. The key was not checked, so it may be valid.';
1643
+ resolution = ['Check your internet connection, VPN, proxy or firewall', 'Run: nansen doctor', 'Try again'];
1644
+ } else if (error.code === ErrorCode.RATE_LIMITED) {
1582
1645
  message = 'Rate limited while verifying the API key.';
1583
1646
  resolution = ['Wait a moment, then retry explicit key setup: nansen login --human'];
1584
1647
  } else if (error.code === ErrorCode.SERVER_ERROR || error.code === ErrorCode.SERVICE_UNAVAILABLE) {
@@ -1727,10 +1790,7 @@ export function buildCommands(deps = {}) {
1727
1790
  };
1728
1791
 
1729
1792
  if (!Object.hasOwn(handlers, subcommand)) {
1730
- throw new NansenError(
1731
- `Unknown cache subcommand: ${subcommand}. Use one of: stats, clear`,
1732
- ErrorCode.INVALID_PARAMS,
1733
- );
1793
+ throw unknownCommandError('cache subcommand', subcommand, ['stats', 'clear']);
1734
1794
  }
1735
1795
 
1736
1796
  const maxArgs = subcommand === 'clear' ? 2 : 1;
@@ -1749,16 +1809,23 @@ export function buildCommands(deps = {}) {
1749
1809
  rejectBlankOption(options.chains, 'chains', 'solana');
1750
1810
  const subcommand = args[0] || 'help';
1751
1811
  const chain = options.chain || 'solana';
1752
- const chains = options.chains || [chain];
1753
- const filters = parseObjectOption(options.filters, 'filters');
1812
+ const chains = parseCsvOption(options.chains, 'chains') || [chain];
1813
+ const filters = parseFiltersOption(options.filters);
1754
1814
  const orderBy = parseSort(options.sort, options['order-by']);
1755
1815
  const pagination = buildPagination(options);
1756
1816
 
1817
+ // `--token` narrows holdings to one token (the API filter token_address).
1818
+ if (subcommand === 'holdings' && options.token !== undefined) {
1819
+ if (typeof options.token !== 'string' || !options.token.trim()) {
1820
+ throw new NansenError('--token requires a token address', ErrorCode.MISSING_PARAM);
1821
+ }
1822
+ filters.token_address = normalizeFilterAddresses(options.token.trim());
1823
+ }
1824
+
1757
1825
  // Add smart money label filter if specified
1758
- if (options.labels) {
1759
- filters.include_smart_money_labels = Array.isArray(options.labels)
1760
- ? options.labels
1761
- : [options.labels];
1826
+ const labels = parseCsvOption(options.labels, 'labels');
1827
+ if (labels?.length) {
1828
+ filters.include_smart_money_labels = labels;
1762
1829
  }
1763
1830
 
1764
1831
  const days = subcommand === 'historical-holdings'
@@ -1775,12 +1842,12 @@ export function buildCommands(deps = {}) {
1775
1842
  'help': () => ({
1776
1843
  commands: ['netflow', 'dex-trades', 'perp-trades', 'holdings', 'dcas', 'historical-holdings'],
1777
1844
  description: 'Smart Money analytics endpoints',
1778
- example: 'nansen smart-money netflow --chain solana --labels Fund'
1845
+ example: 'nansen research smart-money netflow --chain solana --labels "Smart Trader"'
1779
1846
  })
1780
1847
  };
1781
1848
 
1782
- if (!handlers[subcommand]) {
1783
- return { error: `Unknown subcommand: ${subcommand}`, available: Object.keys(handlers) };
1849
+ if (!Object.hasOwn(handlers, subcommand)) {
1850
+ throw unknownCommandError('smart-money subcommand', subcommand, Object.keys(handlers).filter(name => name !== 'help'));
1784
1851
  }
1785
1852
 
1786
1853
  return handlers[subcommand]();
@@ -1806,7 +1873,7 @@ export function buildCommands(deps = {}) {
1806
1873
  throw new NansenError(err.message, ErrorCode.INVALID_ADDRESS);
1807
1874
  }
1808
1875
  }
1809
- const filters = parseObjectOption(options.filters, 'filters');
1876
+ const filters = parseFiltersOption(options.filters);
1810
1877
  const orderBy = parseSort(options.sort, options['order-by']);
1811
1878
  const pagination = buildPagination(options);
1812
1879
  const days = [
@@ -1825,7 +1892,7 @@ export function buildCommands(deps = {}) {
1825
1892
  : 30;
1826
1893
 
1827
1894
  const handlers = {
1828
- 'balance': () => apiInstance.addressBalance({ address, entityName, chain, filters, orderBy }),
1895
+ 'balance': () => apiInstance.addressBalance({ address, entityName, chain, filters, orderBy, pagination }),
1829
1896
  'labels': () => apiInstance.addressLabels({ address, chain, pagination }),
1830
1897
  'transactions': () => {
1831
1898
  const date = parseDateOption(options.date, days, flags.date);
@@ -1846,7 +1913,7 @@ export function buildCommands(deps = {}) {
1846
1913
  : (options.file ? readAddressFile(options.file) : []);
1847
1914
  return apiInstance.addressCounterpartiesBatch({ addresses, chain, filters, orderBy, pagination, days });
1848
1915
  },
1849
- 'pnl-summary': () => apiInstance.addressPnlSummary({ address, chain, orderBy, pagination, days }),
1916
+ 'pnl-summary': () => apiInstance.addressPnlSummary({ address, chain, days }),
1850
1917
  'perp-positions': () => apiInstance.addressPerpPositions({ address, filters, orderBy, pagination }),
1851
1918
  'perp-trades': () => apiInstance.addressPerpTrades({ address, filters, orderBy, pagination, days }),
1852
1919
  'dex-trades': () => {
@@ -1888,8 +1955,8 @@ export function buildCommands(deps = {}) {
1888
1955
  })
1889
1956
  };
1890
1957
 
1891
- if (!handlers[subcommand]) {
1892
- return { error: `Unknown subcommand: ${subcommand}`, available: Object.keys(handlers) };
1958
+ if (!Object.hasOwn(handlers, subcommand)) {
1959
+ throw unknownCommandError('profiler subcommand', subcommand, Object.keys(handlers).filter(name => name !== 'help'));
1893
1960
  }
1894
1961
 
1895
1962
  const result = await handlers[subcommand]();
@@ -1910,11 +1977,12 @@ export function buildCommands(deps = {}) {
1910
1977
  const chain = options.chain || 'solana';
1911
1978
  const tokenAddress = normalizeAddress(options.token || options['token-address'], chain);
1912
1979
  const tokenSymbol = options.symbol || options['token-symbol'];
1913
- const chains = options.chains || [chain];
1980
+ const chains = parseCsvOption(options.chains, 'chains') || [chain];
1914
1981
  const timeframe = options.timeframe || '24h';
1915
- const filters = parseObjectOption(options.filters, 'filters');
1982
+ const filters = parseFiltersOption(options.filters);
1916
1983
  const orderBy = parseSort(options.sort, options['order-by']);
1917
- const pagination = buildPagination(options);
1984
+ // top-tokens has its own --limit (a result count, not a page size).
1985
+ const pagination = subcommand === 'top-tokens' ? undefined : buildPagination(options);
1918
1986
  const days = [
1919
1987
  'flows',
1920
1988
  'dex-trades',
@@ -1931,7 +1999,7 @@ export function buildCommands(deps = {}) {
1931
1999
  const onlySmartMoney = resolveBooleanOption(options, flags, 'smart-money') ?? false;
1932
2000
  if (onlySmartMoney) {
1933
2001
  filters.include_smart_money_labels = filters.include_smart_money_labels ||
1934
- ['Fund', 'Smart Trader', '30D Smart Trader', '90D Smart Trader', '180D Smart Trader'];
2002
+ ['Smart Trader', '30D Smart Trader', '90D Smart Trader', '180D Smart Trader'];
1935
2003
  }
1936
2004
 
1937
2005
  const includeStablecoins = resolveBooleanOption(options, flags, 'include-stablecoins');
@@ -2033,8 +2101,8 @@ export function buildCommands(deps = {}) {
2033
2101
  'flow-intelligence': () => apiInstance.tokenFlowIntelligence({ tokenAddress, chain, timeframe: options.timeframe || '1d' }),
2034
2102
  'transfers': () => {
2035
2103
  // Inject --from/--to into filters
2036
- if (options.from) filters.from_address = options.from;
2037
- if (options.to) filters.to_address = options.to;
2104
+ if (options.from) filters.from_address = normalizeFilterAddresses(options.from);
2105
+ if (options.to) filters.to_address = normalizeFilterAddresses(options.to);
2038
2106
  return apiInstance.tokenTransfers({ tokenAddress, chain, filters, orderBy, pagination, days });
2039
2107
  },
2040
2108
  'jup-dca': () => apiInstance.tokenJupDca({ tokenAddress, filters, orderBy, pagination }),
@@ -2056,8 +2124,8 @@ export function buildCommands(deps = {}) {
2056
2124
  })
2057
2125
  };
2058
2126
 
2059
- if (!handlers[subcommand]) {
2060
- return { error: `Unknown subcommand: ${subcommand}`, available: Object.keys(handlers) };
2127
+ if (!Object.hasOwn(handlers, subcommand)) {
2128
+ throw unknownCommandError('token subcommand', subcommand, Object.keys(handlers).filter(name => name !== 'help'));
2061
2129
  }
2062
2130
 
2063
2131
  let result = await handlers[subcommand]();
@@ -2116,8 +2184,8 @@ export function buildCommands(deps = {}) {
2116
2184
  })
2117
2185
  };
2118
2186
 
2119
- if (!handlers[subcommand]) {
2120
- return { error: `Unknown subcommand: ${subcommand}`, available: Object.keys(handlers) };
2187
+ if (!Object.hasOwn(handlers, subcommand)) {
2188
+ throw unknownCommandError('portfolio subcommand', subcommand, Object.keys(handlers).filter(name => name !== 'help'));
2121
2189
  }
2122
2190
 
2123
2191
  return handlers[subcommand]();
@@ -2126,7 +2194,7 @@ export function buildCommands(deps = {}) {
2126
2194
  'perp': async (args, apiInstance, flags, options) => {
2127
2195
  rejectBlankOption(options.days, 'days', '30');
2128
2196
  const subcommand = args[0] || 'help';
2129
- const filters = parseObjectOption(options.filters, 'filters');
2197
+ const filters = parseFiltersOption(options.filters);
2130
2198
  const orderBy = parseSort(options.sort, options['order-by']);
2131
2199
  const pagination = buildPagination(options);
2132
2200
  const days = ['screener', 'leaderboard'].includes(subcommand)
@@ -2152,8 +2220,8 @@ export function buildCommands(deps = {}) {
2152
2220
  })
2153
2221
  };
2154
2222
 
2155
- if (!handlers[subcommand]) {
2156
- throw new NansenError(`Unknown perp analytics subcommand: ${subcommand}. Available: screener, leaderboard`, ErrorCode.UNKNOWN);
2223
+ if (!Object.hasOwn(handlers, subcommand)) {
2224
+ throw unknownCommandError('perp analytics subcommand', subcommand, ['screener', 'leaderboard']);
2157
2225
  }
2158
2226
 
2159
2227
  return handlers[subcommand]();
@@ -2191,10 +2259,8 @@ export function buildCommands(deps = {}) {
2191
2259
  const tags = parseCsvOption(options.tags, 'tags');
2192
2260
  const minLiquidity = isScreener ? parseFiniteNumberOption('min-liquidity', options, flags) : undefined;
2193
2261
  const maxLiquidity = isScreener ? parseFiniteNumberOption('max-liquidity', options, flags) : undefined;
2194
- const minUniqueTraders24h = isScreener ? parseFiniteNumberOption('min-unique-traders-24h', options, flags) : undefined;
2195
2262
  const maxUniqueTraders24h = isScreener ? parseFiniteNumberOption('max-unique-traders-24h', options, flags) : undefined;
2196
2263
  const minVolume24hr = isScreener ? parseFiniteNumberOption('min-volume-24hr', options, flags) : undefined;
2197
- const maxVolume24hr = isScreener ? parseFiniteNumberOption('max-volume-24hr', options, flags) : undefined;
2198
2264
  const negRisk = resolveBooleanOption(options, flags, 'neg-risk');
2199
2265
  const minOpenInterest = isScreener ? parseFiniteNumberOption('min-open-interest', options, flags) : undefined;
2200
2266
  const maxOpenInterest = isScreener ? parseFiniteNumberOption('max-open-interest', options, flags) : undefined;
@@ -2209,8 +2275,8 @@ export function buildCommands(deps = {}) {
2209
2275
  'top-holders': () => apiInstance.pmTopHolders({ marketId, orderBy, pagination }),
2210
2276
  'trades-by-market': () => apiInstance.pmTradesByMarket({ marketId, orderBy, pagination }),
2211
2277
  'trades-by-address': () => apiInstance.pmTradesByAddress({ address, orderBy, pagination }),
2212
- 'market-screener': () => apiInstance.pmMarketScreener({ orderBy, sortBy, query, status, tags, minLiquidity, maxLiquidity, minUniqueTraders24h, maxUniqueTraders24h, minVolume24hr, maxVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, minPrice, maxPrice, pagination }),
2213
- 'event-screener': () => apiInstance.pmEventScreener({ orderBy, sortBy, query, status, tags, minLiquidity, maxLiquidity, minUniqueTraders24h, maxUniqueTraders24h, minVolume24hr, maxVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, pagination }),
2278
+ 'market-screener': () => apiInstance.pmMarketScreener({ orderBy, sortBy, query, status, tags, minLiquidity, maxLiquidity, maxUniqueTraders24h, minVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, minPrice, maxPrice, pagination }),
2279
+ 'event-screener': () => apiInstance.pmEventScreener({ orderBy, sortBy, query, status, tags, minLiquidity, maxLiquidity, maxUniqueTraders24h, minVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, pagination }),
2214
2280
  'pnl-by-market': () => apiInstance.pmPnlByMarket({ marketId, orderBy, pagination }),
2215
2281
  'pnl-by-address': () => apiInstance.pmPnlByAddress({ address, orderBy, pagination }),
2216
2282
  'position-detail': () => apiInstance.pmPositionDetail({ marketId, pagination }),
@@ -2223,8 +2289,8 @@ export function buildCommands(deps = {}) {
2223
2289
  })
2224
2290
  };
2225
2291
 
2226
- if (!handlers[subcommand]) {
2227
- throw new NansenError(`Unknown subcommand: ${subcommand}. Available: ${Object.keys(handlers).filter(k => k !== 'help').join(', ')}`, ErrorCode.UNKNOWN);
2292
+ if (!Object.hasOwn(handlers, subcommand)) {
2293
+ throw unknownCommandError('prediction-market subcommand', subcommand, Object.keys(handlers).filter(k => k !== 'help'));
2228
2294
  }
2229
2295
 
2230
2296
  return handlers[subcommand]();
@@ -2258,7 +2324,7 @@ export function buildCommands(deps = {}) {
2258
2324
  }
2259
2325
  const category = RESEARCH_CATEGORY_ALIASES[rawCategory] || rawCategory;
2260
2326
  if (!RESEARCH_CATEGORIES.has(category)) {
2261
- throw new NansenError(`Unknown research category: ${rawCategory}. Available: ${[...RESEARCH_CATEGORIES, ...RESEARCH_SUBCOMMANDS].join(', ')}`, ErrorCode.UNKNOWN);
2327
+ throw unknownCommandError('research category', rawCategory, [...RESEARCH_CATEGORIES, ...RESEARCH_SUBCOMMANDS]);
2262
2328
  }
2263
2329
  // `research perp` reaches only the analytics half (screener/leaderboard) —
2264
2330
  // the trading subcommands live at the top level. Use the captured handler
@@ -2299,12 +2365,12 @@ USAGE:
2299
2365
  return;
2300
2366
  }
2301
2367
  if (!limitOrderCmds[loSub]) {
2302
- throw new NansenError(`Unknown limit-order subcommand: ${loSub}. Available: create, list, cancel, update`, ErrorCode.UNKNOWN);
2368
+ throw unknownCommandError('limit-order subcommand', loSub, ['create', 'list', 'cancel', 'update']);
2303
2369
  }
2304
2370
  return limitOrderCmds[loSub](args.slice(2), apiInstance, flags, options);
2305
2371
  }
2306
2372
  if (!tradingCmds[sub]) {
2307
- throw new NansenError(`Unknown trade subcommand: ${sub}. Available: quote, execute, bridge-status, limit-order`, ErrorCode.UNKNOWN);
2373
+ throw unknownCommandError('trade subcommand', sub, ['quote', 'execute', 'bridge-status', 'limit-order']);
2308
2374
  }
2309
2375
  return tradingCmds[sub](args.slice(1), apiInstance, flags, options);
2310
2376
  };
@@ -2336,7 +2402,7 @@ SUPPORTED ROUTES:
2336
2402
  return;
2337
2403
  }
2338
2404
  if (!bridgeCmds[sub]) {
2339
- throw new NansenError(`Unknown bridge subcommand: ${sub}. Available: quote, execute, status`, ErrorCode.UNKNOWN);
2405
+ throw unknownCommandError('bridge subcommand', sub, ['quote', 'execute', 'status']);
2340
2406
  }
2341
2407
  return bridgeCmds[sub](args.slice(1), apiInstance, flags, options);
2342
2408
  };
@@ -2381,7 +2447,7 @@ USAGE:
2381
2447
  if (PERP_ANALYTICS_SUBCOMMANDS.has(sub)) {
2382
2448
  return perpAnalytics(args, apiInstance, flags, options);
2383
2449
  }
2384
- throw new NansenError(`Unknown perp subcommand: ${sub}. Available: order, cancel, close, leverage, transfer, approve-builder-fee, positions, orders, account, meta, screener, leaderboard`, ErrorCode.UNKNOWN);
2450
+ throw unknownCommandError('perp subcommand', sub, ['order', 'cancel', 'close', 'leverage', 'transfer', 'approve-builder-fee', 'positions', 'orders', 'account', 'meta', 'screener', 'leaderboard']);
2385
2451
  }
2386
2452
  return perpCmds[sub](args.slice(1), apiInstance, flags, options);
2387
2453
  };
@@ -2412,6 +2478,22 @@ export const RESEARCH_CATEGORY_ALIASES = {
2412
2478
  'pm': 'prediction-market'
2413
2479
  };
2414
2480
 
2481
+ // Cost lines for help: the base cost, then each spec variant that costs
2482
+ // something different. Variant keys are API conditions such as
2483
+ // "premium_labels=true"; name the CLI flag instead when this command has it.
2484
+ function costHelpLines(endpoint, options = {}) {
2485
+ const cost = getCostForEndpoint(endpoint);
2486
+ if (!cost) return [];
2487
+ const lines = [`Cost: ${formatCost(cost)}`];
2488
+ for (const [condition, variant] of Object.entries(getCostVariants(endpoint) ?? {})) {
2489
+ if (variant.free === cost.free && variant.pro === cost.pro) continue;
2490
+ const flag = condition.match(/^(\w+)=true$/)?.[1].replace(/_/g, '-');
2491
+ const label = flag && options[flag] ? `--${flag}` : condition;
2492
+ lines.push(`Cost with ${label}: ${formatCost(variant)}`);
2493
+ }
2494
+ return lines;
2495
+ }
2496
+
2415
2497
  // Generate help text for a specific subcommand using SCHEMA
2416
2498
  export function generateSubcommandHelp(command, subcommand, prefix = null) {
2417
2499
  // `perp` is both a top-level trading command and a research category, and
@@ -2420,7 +2502,8 @@ export function generateSubcommandHelp(command, subcommand, prefix = null) {
2420
2502
  // stopping at the first schema whose *name* matches — that made
2421
2503
  // `research perp screener --help` fall back to listing the category's
2422
2504
  // subcommands, i.e. telling the caller to run the command they just ran.
2423
- const topSchema = SCHEMA.commands[command];
2505
+ const [group, ...parents] = command.split(' ');
2506
+ const topSchema = parents.reduce((schema, name) => schema?.subcommands?.[name], SCHEMA.commands[group]);
2424
2507
  const researchSchema = SCHEMA.commands.research.subcommands[command];
2425
2508
  const fromResearch = !topSchema?.subcommands?.[subcommand] && Boolean(researchSchema?.subcommands?.[subcommand]);
2426
2509
  const cmdSchema = fromResearch ? researchSchema : topSchema || researchSchema;
@@ -2431,29 +2514,58 @@ export function generateSubcommandHelp(command, subcommand, prefix = null) {
2431
2514
 
2432
2515
  const lines = [];
2433
2516
  lines.push(`${command} ${subcommand} — ${subSchema.description || 'No description'}`);
2517
+ if (subSchema.subcommands) {
2518
+ lines.push('Subcommands: ' + Object.keys(subSchema.subcommands).join(', '));
2519
+ lines.push(`Use: nansen ${command} ${subcommand} <subcommand> --help`);
2520
+ return lines.join('\n');
2521
+ }
2434
2522
 
2435
- if (subSchema.options) {
2436
- const params = Object.entries(subSchema.options).map(([name, opt]) => {
2437
- const parts = [`--${name}`];
2438
- if (opt.required) parts[0] += '*';
2523
+ const positional = subSchema.args ?? [];
2524
+ if (subSchema.options || positional.length) {
2525
+ const describe = (label, opt) => {
2526
+ const parts = [`${label}${opt.required ? '*' : ''}`];
2439
2527
  if (opt.default !== undefined) parts.push(`(${opt.default})`);
2440
2528
  if (opt.enum) parts.push(`[${opt.enum.join('|')}]`);
2529
+ if (command.startsWith('trade') && opt.description) parts.push(`— ${opt.description}`);
2441
2530
  return parts.join(' ');
2442
- });
2443
- lines.push(`Params (* required): ${params.join(', ')}`);
2531
+ };
2532
+ const params = [
2533
+ ...positional.map(arg => describe(`<${arg.name}>`, arg)),
2534
+ ...Object.entries(subSchema.options ?? {}).map(([name, opt]) => describe(`--${name}`, opt)),
2535
+ ];
2536
+ lines.push(command.startsWith('trade')
2537
+ ? `Options (* required):\n ${params.join('\n ')}`
2538
+ : `Params (* required): ${params.join(', ')}`);
2444
2539
  }
2445
2540
 
2446
- if (subSchema.endpoint) {
2447
- const cost = getCostForEndpoint(subSchema.endpoint);
2448
- if (cost) lines.push(`Cost: ${cost.free} credit${cost.free === 1 ? '' : 's'} (Free tier) / ${cost.pro} credit${cost.pro === 1 ? '' : 's'} (Pro tier)`);
2541
+ if (subSchema.supportedChains?.length) {
2542
+ lines.push(`Chains: ${subSchema.supportedChains.join(', ')}`);
2543
+ }
2544
+ if (subSchema.pagination === false) {
2545
+ lines.push('Pagination: not supported (--limit/--page are rejected)');
2449
2546
  }
2450
2547
 
2548
+ if (subSchema.endpoint) lines.push(...costHelpLines(subSchema.endpoint, subSchema.options));
2549
+
2451
2550
  if (subSchema.returns?.length) {
2452
2551
  lines.push(`Returns: ${subSchema.returns.join(', ')}`);
2453
2552
  }
2454
2553
 
2455
- const exampleValues = { address: '0x...', token: '0x...', query: '"term"', symbol: 'BTC', date: '2024-01-01' };
2554
+ if (subSchema.report) {
2555
+ const fields = Object.entries(subSchema.report.fields);
2556
+ const width = Math.max(...fields.map(([name]) => name.length)) + 3;
2557
+ lines.push(`Report (* required): ${subSchema.report.description}`);
2558
+ for (const [name, field] of fields) {
2559
+ const text = field.enum ? `${field.description} One of: ${field.enum.join(', ')}.` : field.description;
2560
+ lines.push(` ${`${name}${field.required ? '*' : ''}`.padEnd(width)}${text}`);
2561
+ }
2562
+ if (subSchema.report.example) lines.push(`Report example: ${JSON.stringify(subSchema.report.example)}`);
2563
+ }
2564
+
2456
2565
  const chain = subSchema.options?.chain?.default || 'solana';
2566
+ const isSolana = subSchema.options?.chain?.default === 'solana';
2567
+ const exampleAddress = isSolana ? 'So11111111111111111111111111111111111111112' : '0x...';
2568
+ const exampleValues = { address: exampleAddress, token: exampleAddress, query: '"term"', symbol: 'BTC', date: '2024-01-01' };
2457
2569
  const cmdPrefix = prefix || (fromResearch || DEPRECATED_TO_RESEARCH.has(command) ? `research ${command}` : command);
2458
2570
  let example = subSchema.examples?.[0] || `nansen ${cmdPrefix} ${subcommand}`;
2459
2571
  if (!subSchema.examples?.length && subSchema.options) {
@@ -2479,10 +2591,19 @@ function emitResponseMetadata(api, errorOutput) {
2479
2591
  // An aggregate belongs to the primary paginated endpoint even if a composite
2480
2592
  // handler made auxiliary requests afterward and changed lastEndpoint.
2481
2593
  const endpoint = api.paginatedResponseMeta ? api.paginatedEndpoint : api.lastEndpoint;
2594
+ // A cache hit records no response meta; with no live call at all there is
2595
+ // nothing to estimate.
2596
+ if (!responseMeta && api.servedFromCache === true) {
2597
+ errorOutput('Credits: 0 (cached)');
2598
+ return;
2599
+ }
2482
2600
  const charged = creditsCharged(responseMeta, endpoint);
2601
+ // The meta (and endpoint) belong to an earlier live call when the last call
2602
+ // was a cache hit; say so instead of attributing the charge to "this call".
2603
+ const laterCacheHit = !api.paginatedResponseMeta && api.servedFromCache === true;
2483
2604
  if (charged?.source === 'header') {
2484
2605
  const paginationMeta = responseMeta?.pagination;
2485
- let scope = 'this call';
2606
+ let scope = laterCacheHit ? 'live call; the cached call was free' : 'this call';
2486
2607
  if (paginationMeta?.cachedPages > 0 && paginationMeta.livePages > 0) {
2487
2608
  scope = `${paginationMeta.livePages} live of ${paginationMeta.pagesFetched} page requests`;
2488
2609
  } else if (paginationMeta?.livePages > 1) scope = `${paginationMeta.livePages} page requests`;
@@ -2490,7 +2611,9 @@ function emitResponseMetadata(api, errorOutput) {
2490
2611
  else if (paginationMeta?.livePages === 0) scope = 'cached traversal';
2491
2612
  errorOutput(`Credits: ${charged.cost} (${scope})`);
2492
2613
  } else if (charged?.source === 'estimate') {
2493
- errorOutput(`Credits: ~${charged.estimate.free} free / ${charged.estimate.pro} pro (estimated)`);
2614
+ const { free, pro } = charged.estimate;
2615
+ const amount = free === pro ? free : `${free} free / ${pro} pro`;
2616
+ errorOutput(`Credits: ~${amount} (estimated${laterCacheHit ? ', live call; the cached call was free' : ''})`);
2494
2617
  }
2495
2618
  }
2496
2619
 
@@ -2578,7 +2701,8 @@ export async function runCLI(rawArgs, deps = {}) {
2578
2701
  || (command === 'doctor' && flags.offline)
2579
2702
  || isMcpUsage
2580
2703
  || command === 'completion'
2581
- || command === 'cache';
2704
+ || command === 'cache'
2705
+ || (command === 'feedback' && subcommand === 'forget');
2582
2706
  const trackSucceeded = isOfflineCommand ? async () => {} : isAuthMutation ? metadata => trackAuthCommand({ ...metadata, command }) : trackCommandSucceeded;
2583
2707
  const trackFailed = isOfflineCommand ? async () => {} : isAuthMutation ? metadata => trackAuthCommand({ ...metadata, command, failed: true }) : trackCommandFailed;
2584
2708
 
@@ -2604,7 +2728,7 @@ export async function runCLI(rawArgs, deps = {}) {
2604
2728
  // modules retain their existing deps: notably wallet export interprets
2605
2729
  // `isTTY` as stdout visibility when deciding whether to warn about printing
2606
2730
  // private keys, so substituting the stdin signal there changes its semantics.
2607
- 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 };
2731
+ const commands = { ...buildCommands(inputInteractiveDeps), ...buildWalletCommands(deps), ...buildTradingCommands(topLevelTradingDeps), ...buildAlertsCommands(deps), ...buildAgentCommands(deps), ...buildFeedbackCommands({ ...deps, log: deps.log ?? output }), ...buildMcpCommands({ ...deps, log: deps.log ?? output }), ...buildCompletionCommands({ ...deps, log: deps.log ?? output }), ...commandOverrides };
2608
2732
 
2609
2733
  if (flags.version || flags.v) {
2610
2734
  output(VERSION);
@@ -2646,10 +2770,7 @@ export async function runCLI(rawArgs, deps = {}) {
2646
2770
  return parts.join(' ');
2647
2771
  });
2648
2772
  lines.push(`Params (* required): ${params.join(', ')}`);
2649
- if (catSchema.endpoint) {
2650
- const cost = getCostForEndpoint(catSchema.endpoint);
2651
- if (cost) lines.push(`Cost: ${cost.free} credit${cost.free === 1 ? '' : 's'} (Free tier) / ${cost.pro} credit${cost.pro === 1 ? '' : 's'} (Pro tier)`);
2652
- }
2773
+ if (catSchema.endpoint) lines.push(...costHelpLines(catSchema.endpoint, catSchema.options));
2653
2774
  }
2654
2775
  output(lines.join('\n'));
2655
2776
  notify();
@@ -2672,6 +2793,7 @@ export async function runCLI(rawArgs, deps = {}) {
2672
2793
  if (command && cmdSchemaLookup) {
2673
2794
  const cmdSchema = cmdSchemaLookup;
2674
2795
  const lines = [`${command} — ${cmdSchema.description}`];
2796
+ if (command === 'bridge') lines.push(`Supported routes: ${formatBridgeRoutes()}`);
2675
2797
  if (cmdSchema.subcommands) {
2676
2798
  lines.push('Subcommands: ' + Object.keys(cmdSchema.subcommands).join(', '));
2677
2799
  lines.push(`Use: nansen ${command} <subcommand> --help`);
@@ -2707,12 +2829,13 @@ export async function runCLI(rawArgs, deps = {}) {
2707
2829
  return { type: 'command-help', command };
2708
2830
  }
2709
2831
  }
2710
- // The trade group (and the deprecated top-level quote/execute aliases) use
2711
- // handler-based usage rather than schema help. Show it and exit 0, instead of
2712
- // falling through to command execution, which would error on missing required
2713
- // args and exit 1.
2832
+ // Resolve nested trade help and deprecated aliases before command execution.
2833
+ // Keep the overview for the group or an unknown subcommand.
2714
2834
  if (command === 'trade' || DEPRECATED_TO_TRADE.has(command)) {
2715
- output(deprecationNote(command) + TRADE_USAGE);
2835
+ const path = command === 'trade' ? positional.slice(1) : [command];
2836
+ const parent = ['trade', ...path.slice(0, -1)].join(' ');
2837
+ const help = path.length ? generateSubcommandHelp(parent, path.at(-1)) : null;
2838
+ output(deprecationNote(command) + (help || TRADE_USAGE));
2716
2839
  notify();
2717
2840
  return { type: 'command-help', command };
2718
2841
  }
@@ -2738,20 +2861,32 @@ export async function runCLI(rawArgs, deps = {}) {
2738
2861
  // or an unquoted shell variable under zsh (which, unlike bash, does not
2739
2862
  // word-split `$var`). Point the user straight at the cause instead of a bare
2740
2863
  // "Unknown command" that reads like a spurious failure.
2741
- const errorData = {
2742
- error: /\s/.test(command)
2743
- ? `Unknown command: "${command}". This looks like multiple words passed as one argument — check your shell quoting (use \`nansen trade --help\`, not \`nansen "trade --help"\`).`
2744
- : `Unknown command: ${command}`,
2745
- available: Object.keys(commands)
2746
- };
2747
- const formatted = formatOutput(errorData, { pretty, table });
2864
+ const available = Object.keys(commands);
2865
+ const error = /\s/.test(command)
2866
+ ? new NansenError(
2867
+ `Unknown command: "${command}". This looks like multiple words passed as one argument — check your shell quoting (use \`nansen trade --help\`, not \`nansen "trade --help"\`).`,
2868
+ ErrorCode.UNKNOWN_COMMAND, null, { available },
2869
+ )
2870
+ : unknownCommandError('command', command, available);
2871
+ const errorData = formatError(error);
2872
+ const formatted = formatOutput(errorData, { pretty, table, csv });
2748
2873
  output(formatted.text);
2749
- await trackFailed({ command: fullCommand, duration_ms: Date.now() - startTime, error_code: 'UNKNOWN_COMMAND', flags: usedFlags, chain });
2874
+ await trackFailed({ command: fullCommand, duration_ms: Date.now() - startTime, error_code: ErrorCode.UNKNOWN_COMMAND, flags: usedFlags, chain });
2750
2875
  exit(1);
2751
2876
  return { type: 'error', data: errorData };
2752
2877
  }
2753
2878
 
2879
+ let researchCommand;
2754
2880
  try {
2881
+ // One validation path for every research command (API-1080/API-1081):
2882
+ // unknown subcommands and options, missing or blank values, enums, dates
2883
+ // and unsupported chains all fail here, before any request is made.
2884
+ validateOutputOptions({ flags, options });
2885
+ researchCommand = resolveResearchCommand(SCHEMA, command, subArgs);
2886
+ if (researchCommand) {
2887
+ validateResearchInput(researchCommand, { flags, options, endpoints: API_ENDPOINTS, chains: SCHEMA.chains });
2888
+ }
2889
+
2755
2890
  // Configure retry options
2756
2891
  const maxRetries = parseNonNegativeSafeIntegerOption('retries', options, flags, 3);
2757
2892
  const retryOptions = flags['no-retry']
@@ -2818,6 +2953,13 @@ export async function runCLI(rawArgs, deps = {}) {
2818
2953
  return { type: 'no-output', command };
2819
2954
  }
2820
2955
 
2956
+ // Feedback JSON is a complete receipt, even alongside list-format flags.
2957
+ if (command === 'feedback') {
2958
+ output(formatOutput({ success: true, data: result }, { pretty }).text);
2959
+ await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: false, flags: usedFlags, chain });
2960
+ return { type: 'success', data: result };
2961
+ }
2962
+
2821
2963
  // Schema returns data directly (not wrapped in { success, data })
2822
2964
  if (command === 'schema') {
2823
2965
  const formatted = formatOutput(result, { pretty, table: false });
@@ -2826,9 +2968,14 @@ export async function runCLI(rawArgs, deps = {}) {
2826
2968
  return { type: 'schema', data: result };
2827
2969
  }
2828
2970
 
2829
- // Apply field filtering if --fields is specified
2971
+ // Apply field filtering if --fields is specified. A name that matches
2972
+ // nothing is an error, not an empty success (API-1081).
2830
2973
  const fields = parseFields(options.fields);
2831
2974
  if (fields) {
2975
+ validateFieldSelection(result, fields, {
2976
+ path: researchCommand?.path ?? `nansen ${fullCommand}`,
2977
+ returns: researchCommand?.leaf?.returns,
2978
+ });
2832
2979
  result = filterFields(result, fields);
2833
2980
  }
2834
2981
 
@@ -2865,7 +3012,11 @@ export async function runCLI(rawArgs, deps = {}) {
2865
3012
  // data (e.g. PASSWORD_REQUIRED resolution steps) is preserved under `details`,
2866
3013
  // so agents get one consistent shape to branch on regardless of command.
2867
3014
  const errorData = formatError(error);
2868
- if (error.reported) {
3015
+ if (command === 'feedback' && !flags.json && !pretty) {
3016
+ output(feedbackErrorText(error));
3017
+ } else if (command === 'feedback') {
3018
+ output(formatOutput(errorData, { pretty }).text);
3019
+ } else if (error.reported) {
2869
3020
  // The command already printed its full human-readable failure output;
2870
3021
  // emitting the envelope too would produce two output shapes on stdout.
2871
3022
  } else if (isUsageError(errorData, { pretty, table, csv, stream, isTTY })) {