nansen-cli 2.3.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 (71) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +32 -32
  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 +17 -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 +202 -97
  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 +188 -89
  50. package/src/commands/agent.js +2 -3
  51. package/src/commands/alerts.js +277 -9
  52. package/src/commands/feedback.js +98 -37
  53. package/src/commands/mcp.js +1 -1
  54. package/src/commands/research.js +14 -37
  55. package/src/cost-cache.js +33 -7
  56. package/src/doctor.js +14 -5
  57. package/src/error-codes.js +226 -0
  58. package/src/input-validation.js +551 -0
  59. package/src/limit-order.js +12 -3
  60. package/src/perp.js +2 -1
  61. package/src/privy.js +89 -11
  62. package/src/query-options.js +30 -7
  63. package/src/rpc-urls.js +3 -1
  64. package/src/schema.json +1137 -145
  65. package/src/solana-tx.js +4 -0
  66. package/src/trade-validation.js +167 -8
  67. package/src/trading.js +172 -12
  68. package/src/transfer.js +7 -1
  69. package/src/update-check.js +32 -5
  70. package/src/wallet.js +211 -57
  71. package/src/walletconnect-x402.js +14 -8
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
  /**
@@ -18,7 +18,8 @@ import { buildAgentCommands } from './commands/agent.js';
18
18
  import { buildMcpCommands } from './commands/mcp.js';
19
19
  import { buildCompletionCommands } from './commands/completion.js';
20
20
  import { buildResearchCommands, RESEARCH_HISTORICAL_SUBCOMMANDS, RESEARCH_SUBCOMMANDS } from './commands/research.js';
21
- 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';
22
23
  import { enableAutoPagination, DEFAULT_MAX_PAGES, MAX_PAGES_LIMIT, locateRows } from './auto-paginate.js';
23
24
  export { buildPagination, parseSort };
24
25
  import { resolveAddress, isEnsName } from './ens.js';
@@ -26,7 +27,7 @@ import { compareSemver } from './semver.js';
26
27
  import fs from 'fs';
27
28
  import { getUpdateNotification, getUpgradeNotice, scheduleUpdateCheck } from './update-check.js';
28
29
  import { getAuthStatus, runDoctorChecks, runConnectivityChecks, formatDoctorReport } from './doctor.js';
29
- import { refreshCostMapIfStale, getCostForEndpoint, creditsCharged } from './cost-cache.js';
30
+ import { refreshCostMapIfStale, getCostForEndpoint, getCostVariants, formatCost, creditsCharged } from './cost-cache.js';
30
31
  import { collectCacheStats, clearCaches, formatCacheStats, formatCacheClear } from './cache-inspect.js';
31
32
  import { creditWarning, noticeWarnings } from './response-meta.js';
32
33
  import { trackCommandSucceeded, trackCommandFailed, trackAuthCommand } from './telemetry.js';
@@ -40,11 +41,31 @@ const { version: VERSION, engines: ENGINES } = require('../package.json');
40
41
  // ============= Schema Definition =============
41
42
 
42
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
+ }
43
64
 
44
65
  // SCHEMA is the static definition with version injected at runtime.
45
66
  // The schema.json file is the source of truth for command metadata (returns, options, etc.)
46
67
  // and should be updated whenever the API changes — do not edit returns arrays here.
47
- export const SCHEMA = { version: VERSION, ...schemaDefinition };
68
+ export const SCHEMA = { version: VERSION, ...withSupportedChains(schemaDefinition, API_ENDPOINTS) };
48
69
 
49
70
  // ============= Pagination =============
50
71
 
@@ -782,7 +803,8 @@ async function enrichTransfers(result, apiInstance, chain) {
782
803
  */
783
804
  export function parseAddressList(raw) {
784
805
  if (Array.isArray(raw)) {
785
- 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);
786
808
  }
787
809
  if (!raw) return [];
788
810
 
@@ -1183,7 +1205,7 @@ BRIDGE (Hyperliquid):
1183
1205
  nansen bridge quote --from-chain base --to-chain hyperliquid --from-token USDC --amount 1000000
1184
1206
  nansen bridge execute --quote <quoteId>
1185
1207
  nansen bridge status --request-id <id>
1186
- Supports EVM chains (ethereum, base, arbitrum, polygon, bnb) <-> Hyperliquid.
1208
+ Supported routes: ${formatBridgeRoutes()}
1187
1209
 
1188
1210
  EXAMPLES:
1189
1211
  nansen trade quote --chain base --from ETH --to USDC --amount 1000000000000000000
@@ -1198,8 +1220,8 @@ DEPRECATED ALIASES (still work, will be removed in a future version):
1198
1220
 
1199
1221
  Research chains: ${SCHEMA.chains.join(', ')}
1200
1222
  Trade chains: solana, base
1201
- Bridge chains: ethereum, base, arbitrum, polygon, bnb, hyperliquid
1202
- 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)
1203
1225
 
1204
1226
  Docs: https://docs.nansen.ai
1205
1227
  Skills: npx skills add nansen-ai/nansen-cli (agent-optimised docs per command group)
@@ -1247,9 +1269,7 @@ expire on their own, and an unexecuted quote is still spendable. Credentials,
1247
1269
  wallets and config are never changed by this command. CLI startup loads the saved
1248
1270
  config as usual.`;
1249
1271
 
1250
- // Usage text for the `trade` command group. Shared by the trade handler and the
1251
- // --help path in runCLI, so `nansen trade`, `nansen trade <sub> --help`, and the
1252
- // deprecated top-level `quote`/`execute --help` all show the same usage.
1272
+ // Overview for the trade group. Individual subcommand help comes from the schema.
1253
1273
  export const TRADE_USAGE = `nansen trade — DEX trading commands
1254
1274
 
1255
1275
  SUBCOMMANDS:
@@ -1444,7 +1464,7 @@ export function buildCommands(deps = {}) {
1444
1464
  'auth': async (args, _apiInstance, _flags, _options) => {
1445
1465
  const subcommand = args[0] || 'status';
1446
1466
  if (subcommand !== 'status') {
1447
- throw new NansenError(`Unknown auth subcommand: ${subcommand}. Available: status`, ErrorCode.UNKNOWN);
1467
+ throw unknownCommandError('auth subcommand', subcommand, ['status']);
1448
1468
  }
1449
1469
  return getAuthStatus();
1450
1470
  },
@@ -1537,8 +1557,8 @@ export function buildCommands(deps = {}) {
1537
1557
  }),
1538
1558
  };
1539
1559
 
1540
- if (!handlers[subcommand]) {
1541
- 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']);
1542
1562
  }
1543
1563
 
1544
1564
  return handlers[subcommand]();
@@ -1554,7 +1574,7 @@ export function buildCommands(deps = {}) {
1554
1574
  if ('api-key' in options && typeof options['api-key'] !== 'string') throw new CommandError('--api-key must be a single key string.', 'INVALID_PARAMS');
1555
1575
  if (!fromStdin && !flags.human && options['api-key'] === undefined) {
1556
1576
  if (!stdinTTY || !stdoutTTY) {
1557
- 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');
1558
1578
  }
1559
1579
  return browserLoginFn({ flags, env, isTTY: stdoutTTY, log, errorOutput, state: authState });
1560
1580
  }
@@ -1618,7 +1638,10 @@ export function buildCommands(deps = {}) {
1618
1638
  // with it). A transient failure shouldn't read as "check your key".
1619
1639
  let message = 'Could not verify API key.';
1620
1640
  let resolution = ['Check your internet connection', 'Try again'];
1621
- 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) {
1622
1645
  message = 'Rate limited while verifying the API key.';
1623
1646
  resolution = ['Wait a moment, then retry explicit key setup: nansen login --human'];
1624
1647
  } else if (error.code === ErrorCode.SERVER_ERROR || error.code === ErrorCode.SERVICE_UNAVAILABLE) {
@@ -1767,10 +1790,7 @@ export function buildCommands(deps = {}) {
1767
1790
  };
1768
1791
 
1769
1792
  if (!Object.hasOwn(handlers, subcommand)) {
1770
- throw new NansenError(
1771
- `Unknown cache subcommand: ${subcommand}. Use one of: stats, clear`,
1772
- ErrorCode.INVALID_PARAMS,
1773
- );
1793
+ throw unknownCommandError('cache subcommand', subcommand, ['stats', 'clear']);
1774
1794
  }
1775
1795
 
1776
1796
  const maxArgs = subcommand === 'clear' ? 2 : 1;
@@ -1789,16 +1809,23 @@ export function buildCommands(deps = {}) {
1789
1809
  rejectBlankOption(options.chains, 'chains', 'solana');
1790
1810
  const subcommand = args[0] || 'help';
1791
1811
  const chain = options.chain || 'solana';
1792
- const chains = options.chains || [chain];
1793
- const filters = parseObjectOption(options.filters, 'filters');
1812
+ const chains = parseCsvOption(options.chains, 'chains') || [chain];
1813
+ const filters = parseFiltersOption(options.filters);
1794
1814
  const orderBy = parseSort(options.sort, options['order-by']);
1795
1815
  const pagination = buildPagination(options);
1796
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
+
1797
1825
  // Add smart money label filter if specified
1798
- if (options.labels) {
1799
- filters.include_smart_money_labels = Array.isArray(options.labels)
1800
- ? options.labels
1801
- : [options.labels];
1826
+ const labels = parseCsvOption(options.labels, 'labels');
1827
+ if (labels?.length) {
1828
+ filters.include_smart_money_labels = labels;
1802
1829
  }
1803
1830
 
1804
1831
  const days = subcommand === 'historical-holdings'
@@ -1815,12 +1842,12 @@ export function buildCommands(deps = {}) {
1815
1842
  'help': () => ({
1816
1843
  commands: ['netflow', 'dex-trades', 'perp-trades', 'holdings', 'dcas', 'historical-holdings'],
1817
1844
  description: 'Smart Money analytics endpoints',
1818
- example: 'nansen smart-money netflow --chain solana --labels Fund'
1845
+ example: 'nansen research smart-money netflow --chain solana --labels "Smart Trader"'
1819
1846
  })
1820
1847
  };
1821
1848
 
1822
- if (!handlers[subcommand]) {
1823
- 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'));
1824
1851
  }
1825
1852
 
1826
1853
  return handlers[subcommand]();
@@ -1846,7 +1873,7 @@ export function buildCommands(deps = {}) {
1846
1873
  throw new NansenError(err.message, ErrorCode.INVALID_ADDRESS);
1847
1874
  }
1848
1875
  }
1849
- const filters = parseObjectOption(options.filters, 'filters');
1876
+ const filters = parseFiltersOption(options.filters);
1850
1877
  const orderBy = parseSort(options.sort, options['order-by']);
1851
1878
  const pagination = buildPagination(options);
1852
1879
  const days = [
@@ -1865,7 +1892,7 @@ export function buildCommands(deps = {}) {
1865
1892
  : 30;
1866
1893
 
1867
1894
  const handlers = {
1868
- 'balance': () => apiInstance.addressBalance({ address, entityName, chain, filters, orderBy }),
1895
+ 'balance': () => apiInstance.addressBalance({ address, entityName, chain, filters, orderBy, pagination }),
1869
1896
  'labels': () => apiInstance.addressLabels({ address, chain, pagination }),
1870
1897
  'transactions': () => {
1871
1898
  const date = parseDateOption(options.date, days, flags.date);
@@ -1886,7 +1913,7 @@ export function buildCommands(deps = {}) {
1886
1913
  : (options.file ? readAddressFile(options.file) : []);
1887
1914
  return apiInstance.addressCounterpartiesBatch({ addresses, chain, filters, orderBy, pagination, days });
1888
1915
  },
1889
- 'pnl-summary': () => apiInstance.addressPnlSummary({ address, chain, orderBy, pagination, days }),
1916
+ 'pnl-summary': () => apiInstance.addressPnlSummary({ address, chain, days }),
1890
1917
  'perp-positions': () => apiInstance.addressPerpPositions({ address, filters, orderBy, pagination }),
1891
1918
  'perp-trades': () => apiInstance.addressPerpTrades({ address, filters, orderBy, pagination, days }),
1892
1919
  'dex-trades': () => {
@@ -1928,8 +1955,8 @@ export function buildCommands(deps = {}) {
1928
1955
  })
1929
1956
  };
1930
1957
 
1931
- if (!handlers[subcommand]) {
1932
- 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'));
1933
1960
  }
1934
1961
 
1935
1962
  const result = await handlers[subcommand]();
@@ -1950,11 +1977,12 @@ export function buildCommands(deps = {}) {
1950
1977
  const chain = options.chain || 'solana';
1951
1978
  const tokenAddress = normalizeAddress(options.token || options['token-address'], chain);
1952
1979
  const tokenSymbol = options.symbol || options['token-symbol'];
1953
- const chains = options.chains || [chain];
1980
+ const chains = parseCsvOption(options.chains, 'chains') || [chain];
1954
1981
  const timeframe = options.timeframe || '24h';
1955
- const filters = parseObjectOption(options.filters, 'filters');
1982
+ const filters = parseFiltersOption(options.filters);
1956
1983
  const orderBy = parseSort(options.sort, options['order-by']);
1957
- 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);
1958
1986
  const days = [
1959
1987
  'flows',
1960
1988
  'dex-trades',
@@ -1971,7 +1999,7 @@ export function buildCommands(deps = {}) {
1971
1999
  const onlySmartMoney = resolveBooleanOption(options, flags, 'smart-money') ?? false;
1972
2000
  if (onlySmartMoney) {
1973
2001
  filters.include_smart_money_labels = filters.include_smart_money_labels ||
1974
- ['Fund', 'Smart Trader', '30D Smart Trader', '90D Smart Trader', '180D Smart Trader'];
2002
+ ['Smart Trader', '30D Smart Trader', '90D Smart Trader', '180D Smart Trader'];
1975
2003
  }
1976
2004
 
1977
2005
  const includeStablecoins = resolveBooleanOption(options, flags, 'include-stablecoins');
@@ -2073,8 +2101,8 @@ export function buildCommands(deps = {}) {
2073
2101
  'flow-intelligence': () => apiInstance.tokenFlowIntelligence({ tokenAddress, chain, timeframe: options.timeframe || '1d' }),
2074
2102
  'transfers': () => {
2075
2103
  // Inject --from/--to into filters
2076
- if (options.from) filters.from_address = options.from;
2077
- 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);
2078
2106
  return apiInstance.tokenTransfers({ tokenAddress, chain, filters, orderBy, pagination, days });
2079
2107
  },
2080
2108
  'jup-dca': () => apiInstance.tokenJupDca({ tokenAddress, filters, orderBy, pagination }),
@@ -2096,8 +2124,8 @@ export function buildCommands(deps = {}) {
2096
2124
  })
2097
2125
  };
2098
2126
 
2099
- if (!handlers[subcommand]) {
2100
- 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'));
2101
2129
  }
2102
2130
 
2103
2131
  let result = await handlers[subcommand]();
@@ -2156,8 +2184,8 @@ export function buildCommands(deps = {}) {
2156
2184
  })
2157
2185
  };
2158
2186
 
2159
- if (!handlers[subcommand]) {
2160
- 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'));
2161
2189
  }
2162
2190
 
2163
2191
  return handlers[subcommand]();
@@ -2166,7 +2194,7 @@ export function buildCommands(deps = {}) {
2166
2194
  'perp': async (args, apiInstance, flags, options) => {
2167
2195
  rejectBlankOption(options.days, 'days', '30');
2168
2196
  const subcommand = args[0] || 'help';
2169
- const filters = parseObjectOption(options.filters, 'filters');
2197
+ const filters = parseFiltersOption(options.filters);
2170
2198
  const orderBy = parseSort(options.sort, options['order-by']);
2171
2199
  const pagination = buildPagination(options);
2172
2200
  const days = ['screener', 'leaderboard'].includes(subcommand)
@@ -2192,8 +2220,8 @@ export function buildCommands(deps = {}) {
2192
2220
  })
2193
2221
  };
2194
2222
 
2195
- if (!handlers[subcommand]) {
2196
- 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']);
2197
2225
  }
2198
2226
 
2199
2227
  return handlers[subcommand]();
@@ -2231,10 +2259,8 @@ export function buildCommands(deps = {}) {
2231
2259
  const tags = parseCsvOption(options.tags, 'tags');
2232
2260
  const minLiquidity = isScreener ? parseFiniteNumberOption('min-liquidity', options, flags) : undefined;
2233
2261
  const maxLiquidity = isScreener ? parseFiniteNumberOption('max-liquidity', options, flags) : undefined;
2234
- const minUniqueTraders24h = isScreener ? parseFiniteNumberOption('min-unique-traders-24h', options, flags) : undefined;
2235
2262
  const maxUniqueTraders24h = isScreener ? parseFiniteNumberOption('max-unique-traders-24h', options, flags) : undefined;
2236
2263
  const minVolume24hr = isScreener ? parseFiniteNumberOption('min-volume-24hr', options, flags) : undefined;
2237
- const maxVolume24hr = isScreener ? parseFiniteNumberOption('max-volume-24hr', options, flags) : undefined;
2238
2264
  const negRisk = resolveBooleanOption(options, flags, 'neg-risk');
2239
2265
  const minOpenInterest = isScreener ? parseFiniteNumberOption('min-open-interest', options, flags) : undefined;
2240
2266
  const maxOpenInterest = isScreener ? parseFiniteNumberOption('max-open-interest', options, flags) : undefined;
@@ -2249,8 +2275,8 @@ export function buildCommands(deps = {}) {
2249
2275
  'top-holders': () => apiInstance.pmTopHolders({ marketId, orderBy, pagination }),
2250
2276
  'trades-by-market': () => apiInstance.pmTradesByMarket({ marketId, orderBy, pagination }),
2251
2277
  'trades-by-address': () => apiInstance.pmTradesByAddress({ address, orderBy, pagination }),
2252
- 'market-screener': () => apiInstance.pmMarketScreener({ orderBy, sortBy, query, status, tags, minLiquidity, maxLiquidity, minUniqueTraders24h, maxUniqueTraders24h, minVolume24hr, maxVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, minPrice, maxPrice, pagination }),
2253
- '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 }),
2254
2280
  'pnl-by-market': () => apiInstance.pmPnlByMarket({ marketId, orderBy, pagination }),
2255
2281
  'pnl-by-address': () => apiInstance.pmPnlByAddress({ address, orderBy, pagination }),
2256
2282
  'position-detail': () => apiInstance.pmPositionDetail({ marketId, pagination }),
@@ -2263,8 +2289,8 @@ export function buildCommands(deps = {}) {
2263
2289
  })
2264
2290
  };
2265
2291
 
2266
- if (!handlers[subcommand]) {
2267
- 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'));
2268
2294
  }
2269
2295
 
2270
2296
  return handlers[subcommand]();
@@ -2298,7 +2324,7 @@ export function buildCommands(deps = {}) {
2298
2324
  }
2299
2325
  const category = RESEARCH_CATEGORY_ALIASES[rawCategory] || rawCategory;
2300
2326
  if (!RESEARCH_CATEGORIES.has(category)) {
2301
- 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]);
2302
2328
  }
2303
2329
  // `research perp` reaches only the analytics half (screener/leaderboard) —
2304
2330
  // the trading subcommands live at the top level. Use the captured handler
@@ -2339,12 +2365,12 @@ USAGE:
2339
2365
  return;
2340
2366
  }
2341
2367
  if (!limitOrderCmds[loSub]) {
2342
- 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']);
2343
2369
  }
2344
2370
  return limitOrderCmds[loSub](args.slice(2), apiInstance, flags, options);
2345
2371
  }
2346
2372
  if (!tradingCmds[sub]) {
2347
- 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']);
2348
2374
  }
2349
2375
  return tradingCmds[sub](args.slice(1), apiInstance, flags, options);
2350
2376
  };
@@ -2376,7 +2402,7 @@ SUPPORTED ROUTES:
2376
2402
  return;
2377
2403
  }
2378
2404
  if (!bridgeCmds[sub]) {
2379
- throw new NansenError(`Unknown bridge subcommand: ${sub}. Available: quote, execute, status`, ErrorCode.UNKNOWN);
2405
+ throw unknownCommandError('bridge subcommand', sub, ['quote', 'execute', 'status']);
2380
2406
  }
2381
2407
  return bridgeCmds[sub](args.slice(1), apiInstance, flags, options);
2382
2408
  };
@@ -2421,7 +2447,7 @@ USAGE:
2421
2447
  if (PERP_ANALYTICS_SUBCOMMANDS.has(sub)) {
2422
2448
  return perpAnalytics(args, apiInstance, flags, options);
2423
2449
  }
2424
- 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']);
2425
2451
  }
2426
2452
  return perpCmds[sub](args.slice(1), apiInstance, flags, options);
2427
2453
  };
@@ -2452,6 +2478,22 @@ export const RESEARCH_CATEGORY_ALIASES = {
2452
2478
  'pm': 'prediction-market'
2453
2479
  };
2454
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
+
2455
2497
  // Generate help text for a specific subcommand using SCHEMA
2456
2498
  export function generateSubcommandHelp(command, subcommand, prefix = null) {
2457
2499
  // `perp` is both a top-level trading command and a research category, and
@@ -2460,7 +2502,8 @@ export function generateSubcommandHelp(command, subcommand, prefix = null) {
2460
2502
  // stopping at the first schema whose *name* matches — that made
2461
2503
  // `research perp screener --help` fall back to listing the category's
2462
2504
  // subcommands, i.e. telling the caller to run the command they just ran.
2463
- const topSchema = SCHEMA.commands[command];
2505
+ const [group, ...parents] = command.split(' ');
2506
+ const topSchema = parents.reduce((schema, name) => schema?.subcommands?.[name], SCHEMA.commands[group]);
2464
2507
  const researchSchema = SCHEMA.commands.research.subcommands[command];
2465
2508
  const fromResearch = !topSchema?.subcommands?.[subcommand] && Boolean(researchSchema?.subcommands?.[subcommand]);
2466
2509
  const cmdSchema = fromResearch ? researchSchema : topSchema || researchSchema;
@@ -2471,29 +2514,58 @@ export function generateSubcommandHelp(command, subcommand, prefix = null) {
2471
2514
 
2472
2515
  const lines = [];
2473
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
+ }
2474
2522
 
2475
- if (subSchema.options) {
2476
- const params = Object.entries(subSchema.options).map(([name, opt]) => {
2477
- const parts = [`--${name}`];
2478
- 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 ? '*' : ''}`];
2479
2527
  if (opt.default !== undefined) parts.push(`(${opt.default})`);
2480
2528
  if (opt.enum) parts.push(`[${opt.enum.join('|')}]`);
2529
+ if (command.startsWith('trade') && opt.description) parts.push(`— ${opt.description}`);
2481
2530
  return parts.join(' ');
2482
- });
2483
- 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(', ')}`);
2484
2539
  }
2485
2540
 
2486
- if (subSchema.endpoint) {
2487
- const cost = getCostForEndpoint(subSchema.endpoint);
2488
- 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(', ')}`);
2489
2543
  }
2544
+ if (subSchema.pagination === false) {
2545
+ lines.push('Pagination: not supported (--limit/--page are rejected)');
2546
+ }
2547
+
2548
+ if (subSchema.endpoint) lines.push(...costHelpLines(subSchema.endpoint, subSchema.options));
2490
2549
 
2491
2550
  if (subSchema.returns?.length) {
2492
2551
  lines.push(`Returns: ${subSchema.returns.join(', ')}`);
2493
2552
  }
2494
2553
 
2495
- 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
+
2496
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' };
2497
2569
  const cmdPrefix = prefix || (fromResearch || DEPRECATED_TO_RESEARCH.has(command) ? `research ${command}` : command);
2498
2570
  let example = subSchema.examples?.[0] || `nansen ${cmdPrefix} ${subcommand}`;
2499
2571
  if (!subSchema.examples?.length && subSchema.options) {
@@ -2519,10 +2591,19 @@ function emitResponseMetadata(api, errorOutput) {
2519
2591
  // An aggregate belongs to the primary paginated endpoint even if a composite
2520
2592
  // handler made auxiliary requests afterward and changed lastEndpoint.
2521
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
+ }
2522
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;
2523
2604
  if (charged?.source === 'header') {
2524
2605
  const paginationMeta = responseMeta?.pagination;
2525
- let scope = 'this call';
2606
+ let scope = laterCacheHit ? 'live call; the cached call was free' : 'this call';
2526
2607
  if (paginationMeta?.cachedPages > 0 && paginationMeta.livePages > 0) {
2527
2608
  scope = `${paginationMeta.livePages} live of ${paginationMeta.pagesFetched} page requests`;
2528
2609
  } else if (paginationMeta?.livePages > 1) scope = `${paginationMeta.livePages} page requests`;
@@ -2530,7 +2611,9 @@ function emitResponseMetadata(api, errorOutput) {
2530
2611
  else if (paginationMeta?.livePages === 0) scope = 'cached traversal';
2531
2612
  errorOutput(`Credits: ${charged.cost} (${scope})`);
2532
2613
  } else if (charged?.source === 'estimate') {
2533
- 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' : ''})`);
2534
2617
  }
2535
2618
  }
2536
2619
 
@@ -2687,10 +2770,7 @@ export async function runCLI(rawArgs, deps = {}) {
2687
2770
  return parts.join(' ');
2688
2771
  });
2689
2772
  lines.push(`Params (* required): ${params.join(', ')}`);
2690
- if (catSchema.endpoint) {
2691
- const cost = getCostForEndpoint(catSchema.endpoint);
2692
- if (cost) lines.push(`Cost: ${cost.free} credit${cost.free === 1 ? '' : 's'} (Free tier) / ${cost.pro} credit${cost.pro === 1 ? '' : 's'} (Pro tier)`);
2693
- }
2773
+ if (catSchema.endpoint) lines.push(...costHelpLines(catSchema.endpoint, catSchema.options));
2694
2774
  }
2695
2775
  output(lines.join('\n'));
2696
2776
  notify();
@@ -2713,6 +2793,7 @@ export async function runCLI(rawArgs, deps = {}) {
2713
2793
  if (command && cmdSchemaLookup) {
2714
2794
  const cmdSchema = cmdSchemaLookup;
2715
2795
  const lines = [`${command} — ${cmdSchema.description}`];
2796
+ if (command === 'bridge') lines.push(`Supported routes: ${formatBridgeRoutes()}`);
2716
2797
  if (cmdSchema.subcommands) {
2717
2798
  lines.push('Subcommands: ' + Object.keys(cmdSchema.subcommands).join(', '));
2718
2799
  lines.push(`Use: nansen ${command} <subcommand> --help`);
@@ -2748,12 +2829,13 @@ export async function runCLI(rawArgs, deps = {}) {
2748
2829
  return { type: 'command-help', command };
2749
2830
  }
2750
2831
  }
2751
- // The trade group (and the deprecated top-level quote/execute aliases) use
2752
- // handler-based usage rather than schema help. Show it and exit 0, instead of
2753
- // falling through to command execution, which would error on missing required
2754
- // 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.
2755
2834
  if (command === 'trade' || DEPRECATED_TO_TRADE.has(command)) {
2756
- 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));
2757
2839
  notify();
2758
2840
  return { type: 'command-help', command };
2759
2841
  }
@@ -2779,20 +2861,32 @@ export async function runCLI(rawArgs, deps = {}) {
2779
2861
  // or an unquoted shell variable under zsh (which, unlike bash, does not
2780
2862
  // word-split `$var`). Point the user straight at the cause instead of a bare
2781
2863
  // "Unknown command" that reads like a spurious failure.
2782
- const errorData = {
2783
- error: /\s/.test(command)
2784
- ? `Unknown command: "${command}". This looks like multiple words passed as one argument — check your shell quoting (use \`nansen trade --help\`, not \`nansen "trade --help"\`).`
2785
- : `Unknown command: ${command}`,
2786
- available: Object.keys(commands)
2787
- };
2788
- 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 });
2789
2873
  output(formatted.text);
2790
- 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 });
2791
2875
  exit(1);
2792
2876
  return { type: 'error', data: errorData };
2793
2877
  }
2794
2878
 
2879
+ let researchCommand;
2795
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
+
2796
2890
  // Configure retry options
2797
2891
  const maxRetries = parseNonNegativeSafeIntegerOption('retries', options, flags, 3);
2798
2892
  const retryOptions = flags['no-retry']
@@ -2874,9 +2968,14 @@ export async function runCLI(rawArgs, deps = {}) {
2874
2968
  return { type: 'schema', data: result };
2875
2969
  }
2876
2970
 
2877
- // 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).
2878
2973
  const fields = parseFields(options.fields);
2879
2974
  if (fields) {
2975
+ validateFieldSelection(result, fields, {
2976
+ path: researchCommand?.path ?? `nansen ${fullCommand}`,
2977
+ returns: researchCommand?.leaf?.returns,
2978
+ });
2880
2979
  result = filterFields(result, fields);
2881
2980
  }
2882
2981
 
@@ -5,7 +5,7 @@
5
5
 
6
6
  import crypto from 'crypto';
7
7
  import { NansenError, ErrorCode, statusToErrorCode, browserSessionError, browserSessionResponseMeta, telemetryHeaders, packageVersion } from '../api.js';
8
- import { getCostForEndpoint } from '../cost-cache.js';
8
+ import { getCostForEndpoint, formatCost } from '../cost-cache.js';
9
9
  import { readResponseMeta } from '../response-meta.js';
10
10
 
11
11
  /**
@@ -167,11 +167,10 @@ export function buildAgentCommands(deps = {}) {
167
167
  'agent': async (args, apiInstance, flags, options) => {
168
168
  // ── Help ──
169
169
  if (flags.help || flags.h || args[0] === 'help' || args.length === 0) {
170
- const fmtCost = (c) => `${c.free} credit${c.free === 1 ? '' : 's'} (Free tier) / ${c.pro} credit${c.pro === 1 ? '' : 's'} (Pro tier)`;
171
170
  const fastCost = getCostForEndpoint('/api/v1/agent/fast');
172
171
  const expertCost = getCostForEndpoint('/api/v1/agent/expert');
173
172
  const costSection = (fastCost || expertCost)
174
- ? `\nCOST:\n${fastCost ? ` fast: ${fmtCost(fastCost)}\n` : ''}${expertCost ? ` expert: ${fmtCost(expertCost)}\n` : ''}`
173
+ ? `\nCOST:\n${fastCost ? ` fast: ${formatCost(fastCost)}\n` : ''}${expertCost ? ` expert: ${formatCost(expertCost)}\n` : ''}`
175
174
  : '';
176
175
  log(`nansen agent — Nansen Research Agent
177
176