nansen-cli 2.3.0 → 2.5.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 (80) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/README.md +61 -38
  3. package/docs/auth.md +56 -0
  4. package/docs/browser-login.md +101 -7
  5. package/docs/error-codes.md +251 -0
  6. package/package.json +10 -4
  7. package/skills/nansen-agent-guide/SKILL.md +20 -4
  8. package/skills/nansen-alerts-webhook-listener/SKILL.md +17 -14
  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 +9 -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 +5 -2
  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 +23 -2
  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 +11 -5
  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 +282 -124
  43. package/src/auth-credentials.js +1 -0
  44. package/src/auth-key-input.js +57 -9
  45. package/src/auth-state.js +2 -2
  46. package/src/auth-store-native.js +6 -1
  47. package/src/auth-store-worker.js +1 -1
  48. package/src/auth-store.js +9 -4
  49. package/src/auto-paginate.js +25 -7
  50. package/src/bridge.js +19 -10
  51. package/src/cache-inspect.js +16 -6
  52. package/src/cli.js +272 -114
  53. package/src/commands/agent.js +2 -3
  54. package/src/commands/alerts.js +365 -18
  55. package/src/commands/completion.js +4 -1
  56. package/src/commands/feedback.js +98 -37
  57. package/src/commands/mcp.js +1 -1
  58. package/src/commands/research.js +14 -37
  59. package/src/cost-cache.js +33 -7
  60. package/src/doctor.js +14 -5
  61. package/src/ens.js +14 -5
  62. package/src/error-codes.js +228 -0
  63. package/src/execute-guard.js +8 -3
  64. package/src/input-validation.js +555 -0
  65. package/src/limit-order.js +127 -54
  66. package/src/perp.js +358 -35
  67. package/src/privy.js +90 -15
  68. package/src/query-options.js +47 -8
  69. package/src/response-cache-files.js +65 -0
  70. package/src/response-meta.js +8 -2
  71. package/src/rpc-urls.js +3 -1
  72. package/src/schema.json +1254 -156
  73. package/src/solana-tx.js +4 -0
  74. package/src/telemetry-flags.js +75 -0
  75. package/src/trade-validation.js +167 -8
  76. package/src/trading.js +243 -20
  77. package/src/transfer.js +79 -12
  78. package/src/update-check.js +32 -5
  79. package/src/wallet.js +246 -69
  80. package/src/walletconnect-x402.js +27 -9
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, UNAVAILABLE_COMMANDS, SUBCOMMAND_ALIASES, 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,11 +27,12 @@ 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';
33
34
  import { setDebugEnabled } from './debug.js';
35
+ import { telemetryFlagNames } from './telemetry-flags.js';
34
36
  import { createRequire } from 'module';
35
37
  import * as readline from 'readline';
36
38
 
@@ -40,11 +42,31 @@ const { version: VERSION, engines: ENGINES } = require('../package.json');
40
42
  // ============= Schema Definition =============
41
43
 
42
44
  const schemaDefinition = require('./schema.json');
45
+ // Chains and request fields per API endpoint, vendored from the public
46
+ // OpenAPI spec by scripts/sync-api-endpoints.js (npm run endpoints:sync).
47
+ export const API_ENDPOINTS = require('./api-endpoints.json').endpoints;
48
+
49
+ /**
50
+ * Add `supportedChains` to every command whose --chain/--chains the API
51
+ * restricts, so `nansen schema` documents the list the CLI enforces. An
52
+ * option with its own `enum` already documents it.
53
+ */
54
+ function withSupportedChains(definition, endpoints) {
55
+ const copy = structuredClone(definition);
56
+ (function walk(node) {
57
+ if (!node || typeof node !== 'object') return;
58
+ const chainOption = node.options?.chain ?? node.options?.chains;
59
+ const chains = endpoints[node.endpoint]?.chains;
60
+ if (chainOption && !chainOption.enum && chains?.length) node.supportedChains = chains;
61
+ for (const child of Object.values(node.subcommands || {})) walk(child);
62
+ })(copy.commands.research);
63
+ return copy;
64
+ }
43
65
 
44
66
  // SCHEMA is the static definition with version injected at runtime.
45
67
  // The schema.json file is the source of truth for command metadata (returns, options, etc.)
46
68
  // and should be updated whenever the API changes — do not edit returns arrays here.
47
- export const SCHEMA = { version: VERSION, ...schemaDefinition };
69
+ export const SCHEMA = { version: VERSION, ...withSupportedChains(schemaDefinition, API_ENDPOINTS) };
48
70
 
49
71
  // ============= Pagination =============
50
72
 
@@ -203,7 +225,7 @@ export function compactSchema(schema) {
203
225
  // rather than swallowing the token after it.
204
226
  export const VALUELESS_FLAGS = new Set([
205
227
  'pretty', 'help', 'version', 'table', 'no-retry', 'cache', 'no-cache', 'stream',
206
- 'enrich', 'full', 'human', 'no-browser', 'api-key-stdin', 'enabled', 'disabled', 'expert', 'json', 'offline',
228
+ 'enrich', 'full', 'human', 'no-browser', 'api-key-stdin', 'webhook-secret-stdin', 'enabled', 'disabled', 'expert', 'json', 'offline',
207
229
  'no-simulate', 'no-verify-outcome', 'no-revoke-excessive-allowance', 'dry-run',
208
230
  'send-api-key', 'all', 'max', 'gasless', 'auto-slippage', 'unsafe-no-password',
209
231
  'reveal', 'yes', 'paginate', 'debug', 'new',
@@ -782,7 +804,8 @@ async function enrichTransfers(result, apiInstance, chain) {
782
804
  */
783
805
  export function parseAddressList(raw) {
784
806
  if (Array.isArray(raw)) {
785
- return raw.map(a => String(a).trim()).filter(Boolean);
807
+ // A repeated flag may carry a list itself (`--addresses a,b --addresses c`).
808
+ return raw.flatMap(a => String(a).split(',')).map(a => a.trim()).filter(Boolean);
786
809
  }
787
810
  if (!raw) return [];
788
811
 
@@ -1183,7 +1206,7 @@ BRIDGE (Hyperliquid):
1183
1206
  nansen bridge quote --from-chain base --to-chain hyperliquid --from-token USDC --amount 1000000
1184
1207
  nansen bridge execute --quote <quoteId>
1185
1208
  nansen bridge status --request-id <id>
1186
- Supports EVM chains (ethereum, base, arbitrum, polygon, bnb) <-> Hyperliquid.
1209
+ Supported routes: ${formatBridgeRoutes()}
1187
1210
 
1188
1211
  EXAMPLES:
1189
1212
  nansen trade quote --chain base --from ETH --to USDC --amount 1000000000000000000
@@ -1198,8 +1221,8 @@ DEPRECATED ALIASES (still work, will be removed in a future version):
1198
1221
 
1199
1222
  Research chains: ${SCHEMA.chains.join(', ')}
1200
1223
  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
1224
+ Bridge routes: ${formatBridgeRoutes()}
1225
+ 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
1226
 
1204
1227
  Docs: https://docs.nansen.ai
1205
1228
  Skills: npx skills add nansen-ai/nansen-cli (agent-optimised docs per command group)
@@ -1247,9 +1270,7 @@ expire on their own, and an unexecuted quote is still spendable. Credentials,
1247
1270
  wallets and config are never changed by this command. CLI startup loads the saved
1248
1271
  config as usual.`;
1249
1272
 
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.
1273
+ // Overview for the trade group. Individual subcommand help comes from the schema.
1253
1274
  export const TRADE_USAGE = `nansen trade — DEX trading commands
1254
1275
 
1255
1276
  SUBCOMMANDS:
@@ -1263,7 +1284,9 @@ USAGE:
1263
1284
  nansen trade quote --chain <chain> --to-chain <chain> --from <token> --to <token> --amount <units>
1264
1285
  nansen trade execute --quote <quoteId> [--wallet <name>] [--dry-run] [--yes]
1265
1286
  nansen trade bridge-status --tx-hash <hash> --from-chain <chain> --to-chain <chain>
1266
- nansen trade limit-order <create|list|cancel|update> [options]
1287
+ nansen trade limit-order create [options] [--dry-run] [--yes]
1288
+ nansen trade limit-order cancel --order <orderId> [--dry-run] [--yes]
1289
+ nansen trade limit-order <list|update> [options]
1267
1290
 
1268
1291
  EXAMPLES:
1269
1292
  nansen trade quote --chain solana --from SOL --to USDC --amount 1000000000
@@ -1278,9 +1301,10 @@ WALLET:
1278
1301
  --wallet <name> Use a named wallet, or "walletconnect" / "wc" for WalletConnect.
1279
1302
  Defaults to the default local wallet if omitted.
1280
1303
 
1281
- BEFORE BROADCASTING (execute only):
1282
- --dry-run Validate and print what would be sent, then stop. Nothing is
1283
- signed or broadcast and the quote stays usable. Exits 0.
1304
+ BEFORE SIGNING (execute and limit-order create/cancel):
1305
+ --dry-run Print the execution or intent plan, then stop before signing
1306
+ or final submission. Limit-order preview makes no API request;
1307
+ cancel preview never requests its one-time transaction. Exits 0.
1284
1308
  --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1). The prompt
1285
1309
  only appears when stdin is a terminal — agents, CI and pipes run
1286
1310
  unprompted either way. Declining exits 1 with nothing signed.
@@ -1444,7 +1468,7 @@ export function buildCommands(deps = {}) {
1444
1468
  'auth': async (args, _apiInstance, _flags, _options) => {
1445
1469
  const subcommand = args[0] || 'status';
1446
1470
  if (subcommand !== 'status') {
1447
- throw new NansenError(`Unknown auth subcommand: ${subcommand}. Available: status`, ErrorCode.UNKNOWN);
1471
+ throw unknownCommandError('auth subcommand', subcommand, ['status']);
1448
1472
  }
1449
1473
  return getAuthStatus();
1450
1474
  },
@@ -1537,8 +1561,8 @@ export function buildCommands(deps = {}) {
1537
1561
  }),
1538
1562
  };
1539
1563
 
1540
- if (!handlers[subcommand]) {
1541
- throw new NansenError(`Unknown web subcommand: ${subcommand}. Available: search, fetch`, ErrorCode.UNKNOWN);
1564
+ if (!Object.hasOwn(handlers, subcommand)) {
1565
+ throw unknownCommandError('web subcommand', subcommand, ['search', 'fetch']);
1542
1566
  }
1543
1567
 
1544
1568
  return handlers[subcommand]();
@@ -1554,7 +1578,7 @@ export function buildCommands(deps = {}) {
1554
1578
  if ('api-key' in options && typeof options['api-key'] !== 'string') throw new CommandError('--api-key must be a single key string.', 'INVALID_PARAMS');
1555
1579
  if (!fromStdin && !flags.human && options['api-key'] === undefined) {
1556
1580
  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');
1581
+ 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
1582
  }
1559
1583
  return browserLoginFn({ flags, env, isTTY: stdoutTTY, log, errorOutput, state: authState });
1560
1584
  }
@@ -1618,7 +1642,10 @@ export function buildCommands(deps = {}) {
1618
1642
  // with it). A transient failure shouldn't read as "check your key".
1619
1643
  let message = 'Could not verify API key.';
1620
1644
  let resolution = ['Check your internet connection', 'Try again'];
1621
- if (error.code === ErrorCode.RATE_LIMITED) {
1645
+ if (error.code === ErrorCode.NETWORK_ERROR) {
1646
+ message = 'Could not reach the Nansen API to verify the API key. The key was not checked, so it may be valid.';
1647
+ resolution = ['Check your internet connection, VPN, proxy or firewall', 'Run: nansen doctor', 'Try again'];
1648
+ } else if (error.code === ErrorCode.RATE_LIMITED) {
1622
1649
  message = 'Rate limited while verifying the API key.';
1623
1650
  resolution = ['Wait a moment, then retry explicit key setup: nansen login --human'];
1624
1651
  } else if (error.code === ErrorCode.SERVER_ERROR || error.code === ErrorCode.SERVICE_UNAVAILABLE) {
@@ -1767,10 +1794,7 @@ export function buildCommands(deps = {}) {
1767
1794
  };
1768
1795
 
1769
1796
  if (!Object.hasOwn(handlers, subcommand)) {
1770
- throw new NansenError(
1771
- `Unknown cache subcommand: ${subcommand}. Use one of: stats, clear`,
1772
- ErrorCode.INVALID_PARAMS,
1773
- );
1797
+ throw unknownCommandError('cache subcommand', subcommand, ['stats', 'clear']);
1774
1798
  }
1775
1799
 
1776
1800
  const maxArgs = subcommand === 'clear' ? 2 : 1;
@@ -1789,16 +1813,23 @@ export function buildCommands(deps = {}) {
1789
1813
  rejectBlankOption(options.chains, 'chains', 'solana');
1790
1814
  const subcommand = args[0] || 'help';
1791
1815
  const chain = options.chain || 'solana';
1792
- const chains = options.chains || [chain];
1793
- const filters = parseObjectOption(options.filters, 'filters');
1816
+ const chains = parseCsvOption(options.chains, 'chains') || [chain];
1817
+ const filters = parseFiltersOption(options.filters);
1794
1818
  const orderBy = parseSort(options.sort, options['order-by']);
1795
1819
  const pagination = buildPagination(options);
1796
1820
 
1821
+ // `--token` narrows holdings to one token (the API filter token_address).
1822
+ if (subcommand === 'holdings' && options.token !== undefined) {
1823
+ if (typeof options.token !== 'string' || !options.token.trim()) {
1824
+ throw new NansenError('--token requires a token address', ErrorCode.MISSING_PARAM);
1825
+ }
1826
+ filters.token_address = normalizeFilterAddresses(options.token.trim());
1827
+ }
1828
+
1797
1829
  // 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];
1830
+ const labels = parseCsvOption(options.labels, 'labels');
1831
+ if (labels?.length) {
1832
+ filters.include_smart_money_labels = labels;
1802
1833
  }
1803
1834
 
1804
1835
  const days = subcommand === 'historical-holdings'
@@ -1815,12 +1846,12 @@ export function buildCommands(deps = {}) {
1815
1846
  'help': () => ({
1816
1847
  commands: ['netflow', 'dex-trades', 'perp-trades', 'holdings', 'dcas', 'historical-holdings'],
1817
1848
  description: 'Smart Money analytics endpoints',
1818
- example: 'nansen smart-money netflow --chain solana --labels Fund'
1849
+ example: 'nansen research smart-money netflow --chain solana --labels "Smart Trader"'
1819
1850
  })
1820
1851
  };
1821
1852
 
1822
- if (!handlers[subcommand]) {
1823
- return { error: `Unknown subcommand: ${subcommand}`, available: Object.keys(handlers) };
1853
+ if (!Object.hasOwn(handlers, subcommand)) {
1854
+ throw unknownCommandError('smart-money subcommand', subcommand, Object.keys(handlers).filter(name => name !== 'help'));
1824
1855
  }
1825
1856
 
1826
1857
  return handlers[subcommand]();
@@ -1846,7 +1877,7 @@ export function buildCommands(deps = {}) {
1846
1877
  throw new NansenError(err.message, ErrorCode.INVALID_ADDRESS);
1847
1878
  }
1848
1879
  }
1849
- const filters = parseObjectOption(options.filters, 'filters');
1880
+ const filters = parseFiltersOption(options.filters);
1850
1881
  const orderBy = parseSort(options.sort, options['order-by']);
1851
1882
  const pagination = buildPagination(options);
1852
1883
  const days = [
@@ -1865,7 +1896,7 @@ export function buildCommands(deps = {}) {
1865
1896
  : 30;
1866
1897
 
1867
1898
  const handlers = {
1868
- 'balance': () => apiInstance.addressBalance({ address, entityName, chain, filters, orderBy }),
1899
+ 'balance': () => apiInstance.addressBalance({ address, entityName, chain, filters, orderBy, pagination }),
1869
1900
  'labels': () => apiInstance.addressLabels({ address, chain, pagination }),
1870
1901
  'transactions': () => {
1871
1902
  const date = parseDateOption(options.date, days, flags.date);
@@ -1886,7 +1917,7 @@ export function buildCommands(deps = {}) {
1886
1917
  : (options.file ? readAddressFile(options.file) : []);
1887
1918
  return apiInstance.addressCounterpartiesBatch({ addresses, chain, filters, orderBy, pagination, days });
1888
1919
  },
1889
- 'pnl-summary': () => apiInstance.addressPnlSummary({ address, chain, orderBy, pagination, days }),
1920
+ 'pnl-summary': () => apiInstance.addressPnlSummary({ address, chain, days }),
1890
1921
  'perp-positions': () => apiInstance.addressPerpPositions({ address, filters, orderBy, pagination }),
1891
1922
  'perp-trades': () => apiInstance.addressPerpTrades({ address, filters, orderBy, pagination, days }),
1892
1923
  'dex-trades': () => {
@@ -1928,8 +1959,8 @@ export function buildCommands(deps = {}) {
1928
1959
  })
1929
1960
  };
1930
1961
 
1931
- if (!handlers[subcommand]) {
1932
- return { error: `Unknown subcommand: ${subcommand}`, available: Object.keys(handlers) };
1962
+ if (!Object.hasOwn(handlers, subcommand)) {
1963
+ throw unknownCommandError('profiler subcommand', subcommand, Object.keys(handlers).filter(name => name !== 'help'));
1933
1964
  }
1934
1965
 
1935
1966
  const result = await handlers[subcommand]();
@@ -1950,11 +1981,12 @@ export function buildCommands(deps = {}) {
1950
1981
  const chain = options.chain || 'solana';
1951
1982
  const tokenAddress = normalizeAddress(options.token || options['token-address'], chain);
1952
1983
  const tokenSymbol = options.symbol || options['token-symbol'];
1953
- const chains = options.chains || [chain];
1984
+ const chains = parseCsvOption(options.chains, 'chains') || [chain];
1954
1985
  const timeframe = options.timeframe || '24h';
1955
- const filters = parseObjectOption(options.filters, 'filters');
1986
+ const filters = parseFiltersOption(options.filters);
1956
1987
  const orderBy = parseSort(options.sort, options['order-by']);
1957
- const pagination = buildPagination(options);
1988
+ // top-tokens has its own --limit (a result count, not a page size).
1989
+ const pagination = subcommand === 'top-tokens' ? undefined : buildPagination(options);
1958
1990
  const days = [
1959
1991
  'flows',
1960
1992
  'dex-trades',
@@ -1971,7 +2003,7 @@ export function buildCommands(deps = {}) {
1971
2003
  const onlySmartMoney = resolveBooleanOption(options, flags, 'smart-money') ?? false;
1972
2004
  if (onlySmartMoney) {
1973
2005
  filters.include_smart_money_labels = filters.include_smart_money_labels ||
1974
- ['Fund', 'Smart Trader', '30D Smart Trader', '90D Smart Trader', '180D Smart Trader'];
2006
+ ['Smart Trader', '30D Smart Trader', '90D Smart Trader', '180D Smart Trader'];
1975
2007
  }
1976
2008
 
1977
2009
  const includeStablecoins = resolveBooleanOption(options, flags, 'include-stablecoins');
@@ -2073,8 +2105,8 @@ export function buildCommands(deps = {}) {
2073
2105
  'flow-intelligence': () => apiInstance.tokenFlowIntelligence({ tokenAddress, chain, timeframe: options.timeframe || '1d' }),
2074
2106
  'transfers': () => {
2075
2107
  // Inject --from/--to into filters
2076
- if (options.from) filters.from_address = options.from;
2077
- if (options.to) filters.to_address = options.to;
2108
+ if (options.from) filters.from_address = normalizeFilterAddresses(options.from);
2109
+ if (options.to) filters.to_address = normalizeFilterAddresses(options.to);
2078
2110
  return apiInstance.tokenTransfers({ tokenAddress, chain, filters, orderBy, pagination, days });
2079
2111
  },
2080
2112
  'jup-dca': () => apiInstance.tokenJupDca({ tokenAddress, filters, orderBy, pagination }),
@@ -2096,8 +2128,8 @@ export function buildCommands(deps = {}) {
2096
2128
  })
2097
2129
  };
2098
2130
 
2099
- if (!handlers[subcommand]) {
2100
- return { error: `Unknown subcommand: ${subcommand}`, available: Object.keys(handlers) };
2131
+ if (!Object.hasOwn(handlers, subcommand)) {
2132
+ throw unknownCommandError('token subcommand', subcommand, Object.keys(handlers).filter(name => name !== 'help'));
2101
2133
  }
2102
2134
 
2103
2135
  let result = await handlers[subcommand]();
@@ -2156,8 +2188,8 @@ export function buildCommands(deps = {}) {
2156
2188
  })
2157
2189
  };
2158
2190
 
2159
- if (!handlers[subcommand]) {
2160
- return { error: `Unknown subcommand: ${subcommand}`, available: Object.keys(handlers) };
2191
+ if (!Object.hasOwn(handlers, subcommand)) {
2192
+ throw unknownCommandError('portfolio subcommand', subcommand, Object.keys(handlers).filter(name => name !== 'help'));
2161
2193
  }
2162
2194
 
2163
2195
  return handlers[subcommand]();
@@ -2166,7 +2198,7 @@ export function buildCommands(deps = {}) {
2166
2198
  'perp': async (args, apiInstance, flags, options) => {
2167
2199
  rejectBlankOption(options.days, 'days', '30');
2168
2200
  const subcommand = args[0] || 'help';
2169
- const filters = parseObjectOption(options.filters, 'filters');
2201
+ const filters = parseFiltersOption(options.filters);
2170
2202
  const orderBy = parseSort(options.sort, options['order-by']);
2171
2203
  const pagination = buildPagination(options);
2172
2204
  const days = ['screener', 'leaderboard'].includes(subcommand)
@@ -2192,8 +2224,8 @@ export function buildCommands(deps = {}) {
2192
2224
  })
2193
2225
  };
2194
2226
 
2195
- if (!handlers[subcommand]) {
2196
- throw new NansenError(`Unknown perp analytics subcommand: ${subcommand}. Available: screener, leaderboard`, ErrorCode.UNKNOWN);
2227
+ if (!Object.hasOwn(handlers, subcommand)) {
2228
+ throw unknownCommandError('perp analytics subcommand', subcommand, ['screener', 'leaderboard']);
2197
2229
  }
2198
2230
 
2199
2231
  return handlers[subcommand]();
@@ -2231,10 +2263,8 @@ export function buildCommands(deps = {}) {
2231
2263
  const tags = parseCsvOption(options.tags, 'tags');
2232
2264
  const minLiquidity = isScreener ? parseFiniteNumberOption('min-liquidity', options, flags) : undefined;
2233
2265
  const maxLiquidity = isScreener ? parseFiniteNumberOption('max-liquidity', options, flags) : undefined;
2234
- const minUniqueTraders24h = isScreener ? parseFiniteNumberOption('min-unique-traders-24h', options, flags) : undefined;
2235
2266
  const maxUniqueTraders24h = isScreener ? parseFiniteNumberOption('max-unique-traders-24h', options, flags) : undefined;
2236
2267
  const minVolume24hr = isScreener ? parseFiniteNumberOption('min-volume-24hr', options, flags) : undefined;
2237
- const maxVolume24hr = isScreener ? parseFiniteNumberOption('max-volume-24hr', options, flags) : undefined;
2238
2268
  const negRisk = resolveBooleanOption(options, flags, 'neg-risk');
2239
2269
  const minOpenInterest = isScreener ? parseFiniteNumberOption('min-open-interest', options, flags) : undefined;
2240
2270
  const maxOpenInterest = isScreener ? parseFiniteNumberOption('max-open-interest', options, flags) : undefined;
@@ -2249,8 +2279,8 @@ export function buildCommands(deps = {}) {
2249
2279
  'top-holders': () => apiInstance.pmTopHolders({ marketId, orderBy, pagination }),
2250
2280
  'trades-by-market': () => apiInstance.pmTradesByMarket({ marketId, orderBy, pagination }),
2251
2281
  '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 }),
2282
+ 'market-screener': () => apiInstance.pmMarketScreener({ orderBy, sortBy, query, status, tags, minLiquidity, maxLiquidity, maxUniqueTraders24h, minVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, minPrice, maxPrice, pagination }),
2283
+ 'event-screener': () => apiInstance.pmEventScreener({ orderBy, sortBy, query, status, tags, minLiquidity, maxLiquidity, maxUniqueTraders24h, minVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, pagination }),
2254
2284
  'pnl-by-market': () => apiInstance.pmPnlByMarket({ marketId, orderBy, pagination }),
2255
2285
  'pnl-by-address': () => apiInstance.pmPnlByAddress({ address, orderBy, pagination }),
2256
2286
  'position-detail': () => apiInstance.pmPositionDetail({ marketId, pagination }),
@@ -2263,8 +2293,8 @@ export function buildCommands(deps = {}) {
2263
2293
  })
2264
2294
  };
2265
2295
 
2266
- if (!handlers[subcommand]) {
2267
- throw new NansenError(`Unknown subcommand: ${subcommand}. Available: ${Object.keys(handlers).filter(k => k !== 'help').join(', ')}`, ErrorCode.UNKNOWN);
2296
+ if (!Object.hasOwn(handlers, subcommand)) {
2297
+ throw unknownCommandError('prediction-market subcommand', subcommand, Object.keys(handlers).filter(k => k !== 'help'));
2268
2298
  }
2269
2299
 
2270
2300
  return handlers[subcommand]();
@@ -2272,7 +2302,7 @@ export function buildCommands(deps = {}) {
2272
2302
  };
2273
2303
 
2274
2304
  // 'research' delegates to the category handlers defined above
2275
- const RESEARCH_CATEGORIES = new Set(['smart-money', 'profiler', 'token', 'search', 'perp', 'portfolio', 'points', 'prediction-market']);
2305
+ const RESEARCH_CATEGORIES = new Set(['smart-money', 'profiler', 'token', 'search', 'perp', 'portfolio', 'prediction-market']);
2276
2306
 
2277
2307
  // The analytics-only perp handler, captured before the trading wrapper below
2278
2308
  // replaces cmds['perp']. Both the wrapper and the research dispatch route to
@@ -2297,8 +2327,8 @@ export function buildCommands(deps = {}) {
2297
2327
  return researchSub(args, apiInstance, flags, options);
2298
2328
  }
2299
2329
  const category = RESEARCH_CATEGORY_ALIASES[rawCategory] || rawCategory;
2300
- if (!RESEARCH_CATEGORIES.has(category)) {
2301
- throw new NansenError(`Unknown research category: ${rawCategory}. Available: ${[...RESEARCH_CATEGORIES, ...RESEARCH_SUBCOMMANDS].join(', ')}`, ErrorCode.UNKNOWN);
2330
+ if (!RESEARCH_CATEGORIES.has(category) && !UNAVAILABLE_COMMANDS.has(category)) {
2331
+ throw unknownCommandError('research category', rawCategory, [...RESEARCH_CATEGORIES, ...RESEARCH_SUBCOMMANDS]);
2302
2332
  }
2303
2333
  // `research perp` reaches only the analytics half (screener/leaderboard) —
2304
2334
  // the trading subcommands live at the top level. Use the captured handler
@@ -2313,7 +2343,7 @@ export function buildCommands(deps = {}) {
2313
2343
  // 'trade' delegates to quote/execute from buildTradingCommands and limit-order from buildLimitOrderCommands
2314
2344
  const executionDeps = { ...deps, promptFn: confirmationPromptFn };
2315
2345
  const tradingCmds = buildTradingCommands(executionDeps);
2316
- const limitOrderCmds = buildLimitOrderCommands(deps);
2346
+ const limitOrderCmds = buildLimitOrderCommands(executionDeps);
2317
2347
  cmds['trade'] = async (args, apiInstance, flags, options) => {
2318
2348
  const sub = args[0];
2319
2349
  if (!sub || sub === 'help') {
@@ -2332,19 +2362,19 @@ SUBCOMMANDS:
2332
2362
  update Update trigger price or slippage
2333
2363
 
2334
2364
  USAGE:
2335
- nansen trade limit-order create --from <token> --to <token> --amount <units> --trigger-mint <token> --trigger-condition <above|below> --trigger-price <usd>
2365
+ nansen trade limit-order create --from <token> --to <token> --amount <units> --trigger-mint <token> --trigger-condition <above|below> --trigger-price <usd> [--dry-run] [--yes]
2336
2366
  nansen trade limit-order list [--state <active|past>]
2337
- nansen trade limit-order cancel --order <orderId>
2367
+ nansen trade limit-order cancel --order <orderId> [--dry-run] [--yes]
2338
2368
  nansen trade limit-order update --order <orderId> --trigger-price <usd>`);
2339
2369
  return;
2340
2370
  }
2341
2371
  if (!limitOrderCmds[loSub]) {
2342
- throw new NansenError(`Unknown limit-order subcommand: ${loSub}. Available: create, list, cancel, update`, ErrorCode.UNKNOWN);
2372
+ throw unknownCommandError('limit-order subcommand', loSub, ['create', 'list', 'cancel', 'update']);
2343
2373
  }
2344
2374
  return limitOrderCmds[loSub](args.slice(2), apiInstance, flags, options);
2345
2375
  }
2346
2376
  if (!tradingCmds[sub]) {
2347
- throw new NansenError(`Unknown trade subcommand: ${sub}. Available: quote, execute, bridge-status, limit-order`, ErrorCode.UNKNOWN);
2377
+ throw unknownCommandError('trade subcommand', sub, ['quote', 'execute', 'bridge-status', 'limit-order']);
2348
2378
  }
2349
2379
  return tradingCmds[sub](args.slice(1), apiInstance, flags, options);
2350
2380
  };
@@ -2376,7 +2406,7 @@ SUPPORTED ROUTES:
2376
2406
  return;
2377
2407
  }
2378
2408
  if (!bridgeCmds[sub]) {
2379
- throw new NansenError(`Unknown bridge subcommand: ${sub}. Available: quote, execute, status`, ErrorCode.UNKNOWN);
2409
+ throw unknownCommandError('bridge subcommand', sub, ['quote', 'execute', 'status']);
2380
2410
  }
2381
2411
  return bridgeCmds[sub](args.slice(1), apiInstance, flags, options);
2382
2412
  };
@@ -2385,7 +2415,7 @@ SUPPORTED ROUTES:
2385
2415
  // top of the pre-existing perp analytics command, so capture that handler and
2386
2416
  // keep screener/leaderboard reachable instead of shadowing them — both
2387
2417
  // `nansen perp screener` and `nansen research perp screener` route through here.
2388
- const perpCmds = buildPerpCommands(deps);
2418
+ const perpCmds = buildPerpCommands(executionDeps);
2389
2419
  const PERP_ANALYTICS_SUBCOMMANDS = new Set(['screener', 'leaderboard']);
2390
2420
  cmds['perp'] = async (args, apiInstance, flags, options) => {
2391
2421
  const sub = args[0];
@@ -2414,14 +2444,19 @@ USAGE:
2414
2444
  nansen perp transfer --direction spot-to-perp --amount 25
2415
2445
  nansen perp approve-builder-fee
2416
2446
  nansen perp positions
2417
- nansen perp account`);
2447
+ nansen perp account
2448
+
2449
+ BEFORE SUBMITTING (order, cancel, close, leverage):
2450
+ --dry-run Validate and print what would be submitted, then stop. Exits 0.
2451
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1). The prompt only
2452
+ appears when stdin is a terminal; declining exits 1, signing nothing.`);
2418
2453
  return;
2419
2454
  }
2420
2455
  if (!perpCmds[sub]) {
2421
2456
  if (PERP_ANALYTICS_SUBCOMMANDS.has(sub)) {
2422
2457
  return perpAnalytics(args, apiInstance, flags, options);
2423
2458
  }
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);
2459
+ throw unknownCommandError('perp subcommand', sub, ['order', 'cancel', 'close', 'leverage', 'transfer', 'approve-builder-fee', 'positions', 'orders', 'account', 'meta', 'screener', 'leaderboard']);
2425
2460
  }
2426
2461
  return perpCmds[sub](args.slice(1), apiInstance, flags, options);
2427
2462
  };
@@ -2434,6 +2469,31 @@ export const DEPRECATED_TO_RESEARCH = new Set(['smart-money', 'profiler', 'token
2434
2469
  // Subcommands that moved under 'trade'
2435
2470
  export const DEPRECATED_TO_TRADE = new Set(['quote', 'execute']);
2436
2471
 
2472
+ // Subcommands of removed commands (UNAVAILABLE_COMMANDS), which have no schema entry.
2473
+ const REMOVED_SUBCOMMANDS = { points: ['leaderboard'] };
2474
+
2475
+ /**
2476
+ * Command name for telemetry. Positionals are often values (a search query,
2477
+ * an address), so only subcommands listed in the schema are kept.
2478
+ */
2479
+ function telemetryCommandName(commands, command, subcommand) {
2480
+ if (!Object.hasOwn(commands, command)) return 'unknown';
2481
+ if (!subcommand) return command;
2482
+ if (command === 'research') {
2483
+ const category = RESEARCH_CATEGORY_ALIASES[subcommand] || subcommand;
2484
+ const known = Object.hasOwn(SCHEMA.commands.research.subcommands, category) || UNAVAILABLE_COMMANDS.has(category);
2485
+ return known ? `research ${category}` : 'research';
2486
+ }
2487
+ // `perp` is both a top-level command and a research category (screener, leaderboard).
2488
+ const known = [SCHEMA.commands[command]?.subcommands, SCHEMA.commands.research.subcommands[command]?.subcommands];
2489
+ if (known.some(subcommands => subcommands && Object.hasOwn(subcommands, subcommand))
2490
+ || REMOVED_SUBCOMMANDS[command]?.includes(subcommand)
2491
+ || Object.hasOwn(SUBCOMMAND_ALIASES[command] ?? {}, subcommand)) {
2492
+ return `${command} ${subcommand}`;
2493
+ }
2494
+ return command;
2495
+ }
2496
+
2437
2497
  // Command aliases: top-level shortcuts that resolve before routing
2438
2498
  export const COMMAND_ALIASES = {
2439
2499
  'tgm': 'token', // Token God Mode
@@ -2452,6 +2512,22 @@ export const RESEARCH_CATEGORY_ALIASES = {
2452
2512
  'pm': 'prediction-market'
2453
2513
  };
2454
2514
 
2515
+ // Cost lines for help: the base cost, then each spec variant that costs
2516
+ // something different. Variant keys are API conditions such as
2517
+ // "premium_labels=true"; name the CLI flag instead when this command has it.
2518
+ function costHelpLines(endpoint, options = {}) {
2519
+ const cost = getCostForEndpoint(endpoint);
2520
+ if (!cost) return [];
2521
+ const lines = [`Cost: ${formatCost(cost)}`];
2522
+ for (const [condition, variant] of Object.entries(getCostVariants(endpoint) ?? {})) {
2523
+ if (variant.free === cost.free && variant.pro === cost.pro) continue;
2524
+ const flag = condition.match(/^(\w+)=true$/)?.[1].replace(/_/g, '-');
2525
+ const label = flag && options[flag] ? `--${flag}` : condition;
2526
+ lines.push(`Cost with ${label}: ${formatCost(variant)}`);
2527
+ }
2528
+ return lines;
2529
+ }
2530
+
2455
2531
  // Generate help text for a specific subcommand using SCHEMA
2456
2532
  export function generateSubcommandHelp(command, subcommand, prefix = null) {
2457
2533
  // `perp` is both a top-level trading command and a research category, and
@@ -2460,7 +2536,8 @@ export function generateSubcommandHelp(command, subcommand, prefix = null) {
2460
2536
  // stopping at the first schema whose *name* matches — that made
2461
2537
  // `research perp screener --help` fall back to listing the category's
2462
2538
  // subcommands, i.e. telling the caller to run the command they just ran.
2463
- const topSchema = SCHEMA.commands[command];
2539
+ const [group, ...parents] = command.split(' ');
2540
+ const topSchema = parents.reduce((schema, name) => schema?.subcommands?.[name], SCHEMA.commands[group]);
2464
2541
  const researchSchema = SCHEMA.commands.research.subcommands[command];
2465
2542
  const fromResearch = !topSchema?.subcommands?.[subcommand] && Boolean(researchSchema?.subcommands?.[subcommand]);
2466
2543
  const cmdSchema = fromResearch ? researchSchema : topSchema || researchSchema;
@@ -2471,29 +2548,58 @@ export function generateSubcommandHelp(command, subcommand, prefix = null) {
2471
2548
 
2472
2549
  const lines = [];
2473
2550
  lines.push(`${command} ${subcommand} — ${subSchema.description || 'No description'}`);
2551
+ if (subSchema.subcommands) {
2552
+ lines.push('Subcommands: ' + Object.keys(subSchema.subcommands).join(', '));
2553
+ lines.push(`Use: nansen ${command} ${subcommand} <subcommand> --help`);
2554
+ return lines.join('\n');
2555
+ }
2474
2556
 
2475
- if (subSchema.options) {
2476
- const params = Object.entries(subSchema.options).map(([name, opt]) => {
2477
- const parts = [`--${name}`];
2478
- if (opt.required) parts[0] += '*';
2557
+ const positional = subSchema.args ?? [];
2558
+ if (subSchema.options || positional.length) {
2559
+ const describe = (label, opt) => {
2560
+ const parts = [`${label}${opt.required ? '*' : ''}`];
2479
2561
  if (opt.default !== undefined) parts.push(`(${opt.default})`);
2480
2562
  if (opt.enum) parts.push(`[${opt.enum.join('|')}]`);
2563
+ if (command.startsWith('trade') && opt.description) parts.push(`— ${opt.description}`);
2481
2564
  return parts.join(' ');
2482
- });
2483
- lines.push(`Params (* required): ${params.join(', ')}`);
2565
+ };
2566
+ const params = [
2567
+ ...positional.map(arg => describe(`<${arg.name}>`, arg)),
2568
+ ...Object.entries(subSchema.options ?? {}).map(([name, opt]) => describe(`--${name}`, opt)),
2569
+ ];
2570
+ lines.push(command.startsWith('trade')
2571
+ ? `Options (* required):\n ${params.join('\n ')}`
2572
+ : `Params (* required): ${params.join(', ')}`);
2484
2573
  }
2485
2574
 
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)`);
2575
+ if (subSchema.supportedChains?.length) {
2576
+ lines.push(`Chains: ${subSchema.supportedChains.join(', ')}`);
2577
+ }
2578
+ if (subSchema.pagination === false) {
2579
+ lines.push('Pagination: not supported (--limit/--page are rejected)');
2489
2580
  }
2490
2581
 
2582
+ if (subSchema.endpoint) lines.push(...costHelpLines(subSchema.endpoint, subSchema.options));
2583
+
2491
2584
  if (subSchema.returns?.length) {
2492
2585
  lines.push(`Returns: ${subSchema.returns.join(', ')}`);
2493
2586
  }
2494
2587
 
2495
- const exampleValues = { address: '0x...', token: '0x...', query: '"term"', symbol: 'BTC', date: '2024-01-01' };
2588
+ if (subSchema.report) {
2589
+ const fields = Object.entries(subSchema.report.fields);
2590
+ const width = Math.max(...fields.map(([name]) => name.length)) + 3;
2591
+ lines.push(`Report (* required): ${subSchema.report.description}`);
2592
+ for (const [name, field] of fields) {
2593
+ const text = field.enum ? `${field.description} One of: ${field.enum.join(', ')}.` : field.description;
2594
+ lines.push(` ${`${name}${field.required ? '*' : ''}`.padEnd(width)}${text}`);
2595
+ }
2596
+ if (subSchema.report.example) lines.push(`Report example: ${JSON.stringify(subSchema.report.example)}`);
2597
+ }
2598
+
2496
2599
  const chain = subSchema.options?.chain?.default || 'solana';
2600
+ const isSolana = subSchema.options?.chain?.default === 'solana';
2601
+ const exampleAddress = isSolana ? 'So11111111111111111111111111111111111111112' : '0x...';
2602
+ const exampleValues = { address: exampleAddress, token: exampleAddress, query: '"term"', symbol: 'BTC', date: '2024-01-01' };
2497
2603
  const cmdPrefix = prefix || (fromResearch || DEPRECATED_TO_RESEARCH.has(command) ? `research ${command}` : command);
2498
2604
  let example = subSchema.examples?.[0] || `nansen ${cmdPrefix} ${subcommand}`;
2499
2605
  if (!subSchema.examples?.length && subSchema.options) {
@@ -2519,10 +2625,20 @@ function emitResponseMetadata(api, errorOutput) {
2519
2625
  // An aggregate belongs to the primary paginated endpoint even if a composite
2520
2626
  // handler made auxiliary requests afterward and changed lastEndpoint.
2521
2627
  const endpoint = api.paginatedResponseMeta ? api.paginatedEndpoint : api.lastEndpoint;
2628
+ // Cached advisories can supply metadata without any live accounting.
2629
+ // With no live call at all there is nothing to estimate.
2630
+ if (api.servedFromCache === true && !api.paginatedResponseMeta
2631
+ && (!responseMeta || (!responseMeta.credits && !api.lastEndpoint))) {
2632
+ errorOutput('Credits: 0 (cached)');
2633
+ return;
2634
+ }
2522
2635
  const charged = creditsCharged(responseMeta, endpoint);
2636
+ // The meta (and endpoint) belong to an earlier live call when the last call
2637
+ // was a cache hit; say so instead of attributing the charge to "this call".
2638
+ const laterCacheHit = !api.paginatedResponseMeta && api.servedFromCache === true;
2523
2639
  if (charged?.source === 'header') {
2524
2640
  const paginationMeta = responseMeta?.pagination;
2525
- let scope = 'this call';
2641
+ let scope = laterCacheHit ? 'live call; the cached call was free' : 'this call';
2526
2642
  if (paginationMeta?.cachedPages > 0 && paginationMeta.livePages > 0) {
2527
2643
  scope = `${paginationMeta.livePages} live of ${paginationMeta.pagesFetched} page requests`;
2528
2644
  } else if (paginationMeta?.livePages > 1) scope = `${paginationMeta.livePages} page requests`;
@@ -2530,7 +2646,9 @@ function emitResponseMetadata(api, errorOutput) {
2530
2646
  else if (paginationMeta?.livePages === 0) scope = 'cached traversal';
2531
2647
  errorOutput(`Credits: ${charged.cost} (${scope})`);
2532
2648
  } else if (charged?.source === 'estimate') {
2533
- errorOutput(`Credits: ~${charged.estimate.free} free / ${charged.estimate.pro} pro (estimated)`);
2649
+ const { free, pro } = charged.estimate;
2650
+ const amount = free === pro ? free : `${free} free / ${pro} pro`;
2651
+ errorOutput(`Credits: ~${amount} (estimated${laterCacheHit ? ', live call; the cached call was free' : ''})`);
2534
2652
  }
2535
2653
  }
2536
2654
 
@@ -2614,12 +2732,17 @@ export async function runCLI(rawArgs, deps = {}) {
2614
2732
  // recreate update/telemetry state during the same invocation.
2615
2733
  const isMcpUsage = command === 'mcp' && (subcommand !== 'verify' || flags.help || flags.h);
2616
2734
  const isAuthMutation = command === 'login' || command === 'logout';
2735
+ const isOfflineLimitOrderDryRun = command === 'trade'
2736
+ && subArgs[0] === 'limit-order'
2737
+ && (subArgs[1] === 'create' || subArgs[1] === 'cancel')
2738
+ && flags['dry-run'] === true;
2617
2739
  const isOfflineCommand = command === 'auth'
2618
2740
  || (command === 'doctor' && flags.offline)
2619
2741
  || isMcpUsage
2620
2742
  || command === 'completion'
2621
2743
  || command === 'cache'
2622
- || (command === 'feedback' && subcommand === 'forget');
2744
+ || (command === 'feedback' && subcommand === 'forget')
2745
+ || isOfflineLimitOrderDryRun;
2623
2746
  const trackSucceeded = isOfflineCommand ? async () => {} : isAuthMutation ? metadata => trackAuthCommand({ ...metadata, command }) : trackCommandSucceeded;
2624
2747
  const trackFailed = isOfflineCommand ? async () => {} : isAuthMutation ? metadata => trackAuthCommand({ ...metadata, command, failed: true }) : trackCommandFailed;
2625
2748
 
@@ -2652,7 +2775,11 @@ export async function runCLI(rawArgs, deps = {}) {
2652
2775
  return { type: 'version', data: VERSION };
2653
2776
  }
2654
2777
 
2655
- if (command === 'help' || flags.help || flags.h) {
2778
+ // A removed command has no help to show: let its handler answer --help with
2779
+ // the same COMMAND_UNAVAILABLE error, rather than printing a generic listing.
2780
+ const unavailableCommand = UNAVAILABLE_COMMANDS.has(command)
2781
+ || (command === 'research' && UNAVAILABLE_COMMANDS.has(RESEARCH_CATEGORY_ALIASES[subcommand] || subcommand));
2782
+ if (command === 'help' || ((flags.help || flags.h) && !unavailableCommand)) {
2656
2783
  // Help for an offline command still owes the zero-network contract: the
2657
2784
  // cost-map refresh fetches the OpenAPI spec and writes ~/.nansen/cost-map.json.
2658
2785
  if (!isOfflineCommand && !isAuthMutation) await refreshCostMapIfStale();
@@ -2687,10 +2814,7 @@ export async function runCLI(rawArgs, deps = {}) {
2687
2814
  return parts.join(' ');
2688
2815
  });
2689
2816
  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
- }
2817
+ if (catSchema.endpoint) lines.push(...costHelpLines(catSchema.endpoint, catSchema.options));
2694
2818
  }
2695
2819
  output(lines.join('\n'));
2696
2820
  notify();
@@ -2713,6 +2837,7 @@ export async function runCLI(rawArgs, deps = {}) {
2713
2837
  if (command && cmdSchemaLookup) {
2714
2838
  const cmdSchema = cmdSchemaLookup;
2715
2839
  const lines = [`${command} — ${cmdSchema.description}`];
2840
+ if (command === 'bridge') lines.push(`Supported routes: ${formatBridgeRoutes()}`);
2716
2841
  if (cmdSchema.subcommands) {
2717
2842
  lines.push('Subcommands: ' + Object.keys(cmdSchema.subcommands).join(', '));
2718
2843
  lines.push(`Use: nansen ${command} <subcommand> --help`);
@@ -2748,12 +2873,13 @@ export async function runCLI(rawArgs, deps = {}) {
2748
2873
  return { type: 'command-help', command };
2749
2874
  }
2750
2875
  }
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.
2876
+ // Resolve nested trade help and deprecated aliases before command execution.
2877
+ // Keep the overview for the group or an unknown subcommand.
2755
2878
  if (command === 'trade' || DEPRECATED_TO_TRADE.has(command)) {
2756
- output(deprecationNote(command) + TRADE_USAGE);
2879
+ const path = command === 'trade' ? positional.slice(1) : [command];
2880
+ const parent = ['trade', ...path.slice(0, -1)].join(' ');
2881
+ const help = path.length ? generateSubcommandHelp(parent, path.at(-1)) : null;
2882
+ output(deprecationNote(command) + (help || TRADE_USAGE));
2757
2883
  notify();
2758
2884
  return { type: 'command-help', command };
2759
2885
  }
@@ -2768,9 +2894,13 @@ export async function runCLI(rawArgs, deps = {}) {
2768
2894
  // ── Telemetry setup ──
2769
2895
  const startTime = Date.now();
2770
2896
  const fullCommand = subcommand ? `${command} ${subcommand}` : command;
2897
+ const telemetryCommand = telemetryCommandName(commands, command, subcommand);
2771
2898
  const flagNames = Object.keys(flags).filter(k => flags[k]).map(k => `--${k}`);
2772
2899
  const optionNames = Object.keys(options).map(k => `--${k}`);
2773
- const usedFlags = [...flagNames, ...optionNames];
2900
+ // Only names the CLI defines reach telemetry (login/logout keep their own set).
2901
+ const usedFlags = isAuthMutation
2902
+ ? [...flagNames, ...optionNames]
2903
+ : telemetryFlagNames({ schema: SCHEMA, command, subArgs, switches: VALUELESS_FLAGS }, [...flagNames, ...optionNames]);
2774
2904
  const chain = options.chain || null;
2775
2905
 
2776
2906
  if (!commands[command]) {
@@ -2779,20 +2909,32 @@ export async function runCLI(rawArgs, deps = {}) {
2779
2909
  // or an unquoted shell variable under zsh (which, unlike bash, does not
2780
2910
  // word-split `$var`). Point the user straight at the cause instead of a bare
2781
2911
  // "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 });
2912
+ const available = Object.keys(commands).filter(name => !UNAVAILABLE_COMMANDS.has(name));
2913
+ const error = /\s/.test(command)
2914
+ ? new NansenError(
2915
+ `Unknown command: "${command}". This looks like multiple words passed as one argument — check your shell quoting (use \`nansen trade --help\`, not \`nansen "trade --help"\`).`,
2916
+ ErrorCode.UNKNOWN_COMMAND, null, { available },
2917
+ )
2918
+ : unknownCommandError('command', command, available);
2919
+ const errorData = formatError(error);
2920
+ const formatted = formatOutput(errorData, { pretty, table, csv });
2789
2921
  output(formatted.text);
2790
- await trackFailed({ command: fullCommand, duration_ms: Date.now() - startTime, error_code: 'UNKNOWN_COMMAND', flags: usedFlags, chain });
2922
+ await trackFailed({ command: telemetryCommand, duration_ms: Date.now() - startTime, error_code: ErrorCode.UNKNOWN_COMMAND, flags: usedFlags, chain });
2791
2923
  exit(1);
2792
2924
  return { type: 'error', data: errorData };
2793
2925
  }
2794
2926
 
2927
+ let researchCommand;
2795
2928
  try {
2929
+ // One validation path for every research command (API-1080/API-1081):
2930
+ // unknown subcommands and options, missing or blank values, enums, dates
2931
+ // and unsupported chains all fail here, before any request is made.
2932
+ validateOutputOptions({ flags, options });
2933
+ researchCommand = resolveResearchCommand(SCHEMA, command, subArgs);
2934
+ if (researchCommand) {
2935
+ validateResearchInput(researchCommand, { flags, options, endpoints: API_ENDPOINTS, chains: SCHEMA.chains });
2936
+ }
2937
+
2796
2938
  // Configure retry options
2797
2939
  const maxRetries = parseNonNegativeSafeIntegerOption('retries', options, flags, 3);
2798
2940
  const retryOptions = flags['no-retry']
@@ -2813,11 +2955,16 @@ export async function runCLI(rawArgs, deps = {}) {
2813
2955
  if (options['x402-payment-signature']) {
2814
2956
  defaultHeaders['Payment-Signature'] = options['x402-payment-signature'];
2815
2957
  }
2816
- api = new NansenAPIClass(undefined, undefined, { retry: retryOptions, cache: cacheOptions, defaultHeaders, authState: inputInteractiveDeps.authState });
2958
+ // Limit-order dry runs are intentionally local previews. In addition to
2959
+ // suppressing update checks and telemetry above, avoid constructing the API
2960
+ // client because its constructor resolves saved Nansen credentials.
2961
+ if (!isOfflineLimitOrderDryRun) {
2962
+ api = new NansenAPIClass(undefined, undefined, { retry: retryOptions, cache: cacheOptions, defaultHeaders, authState: inputInteractiveDeps.authState });
2963
+ }
2817
2964
 
2818
2965
  // --all aliases --paginate; wrapping api.request gives every list handler
2819
2966
  // the same max-pages bound while leaving non-list requests untouched.
2820
- if (flags.paginate || flags.all) {
2967
+ if ((flags.paginate || flags.all) && api) {
2821
2968
  const maxPages = parsePositiveSafeIntegerOption(
2822
2969
  'max-pages', options, flags, DEFAULT_MAX_PAGES, { max: MAX_PAGES_LIMIT },
2823
2970
  );
@@ -2845,7 +2992,13 @@ export async function runCLI(rawArgs, deps = {}) {
2845
2992
  // on the instance next to the cache-hit early return in request(), so it
2846
2993
  // survives that reshaping. Compared against `true` so a stubbed API whose
2847
2994
  // every property is a mock function doesn't read as a hit.
2848
- const fromCache = !!result?._meta?.fromCache || api.servedFromCache === true;
2995
+ //
2996
+ // A --paginate result mixes pages, and both of those describe a single
2997
+ // page; it was served from the cache only if no page went to the API.
2998
+ const paginatedPages = api?.paginatedResponseMeta?.pagination;
2999
+ const fromCache = paginatedPages
3000
+ ? paginatedPages.livePages === 0
3001
+ : !!result?._meta?.fromCache || api?.servedFromCache === true;
2849
3002
 
2850
3003
  // Credit balance warning, from the headers on the call just made. Goes to
2851
3004
  // stderr so it never contaminates the JSON on stdout that agents parse.
@@ -2855,14 +3008,14 @@ export async function runCLI(rawArgs, deps = {}) {
2855
3008
 
2856
3009
  // Commands that handle their own output return undefined
2857
3010
  if (result === undefined) {
2858
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, flags: usedFlags, chain });
3011
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, flags: usedFlags, chain });
2859
3012
  return { type: 'no-output', command };
2860
3013
  }
2861
3014
 
2862
3015
  // Feedback JSON is a complete receipt, even alongside list-format flags.
2863
3016
  if (command === 'feedback') {
2864
3017
  output(formatOutput({ success: true, data: result }, { pretty }).text);
2865
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: false, flags: usedFlags, chain });
3018
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, from_cache: false, flags: usedFlags, chain });
2866
3019
  return { type: 'success', data: result };
2867
3020
  }
2868
3021
 
@@ -2870,20 +3023,25 @@ export async function runCLI(rawArgs, deps = {}) {
2870
3023
  if (command === 'schema') {
2871
3024
  const formatted = formatOutput(result, { pretty, table: false });
2872
3025
  output(formatted.text);
2873
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, flags: usedFlags, chain });
3026
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, flags: usedFlags, chain });
2874
3027
  return { type: 'schema', data: result };
2875
3028
  }
2876
3029
 
2877
- // Apply field filtering if --fields is specified
3030
+ // Apply field filtering if --fields is specified. A name that matches
3031
+ // nothing is an error, not an empty success (API-1081).
2878
3032
  const fields = parseFields(options.fields);
2879
3033
  if (fields) {
3034
+ validateFieldSelection(result, fields, {
3035
+ path: researchCommand?.path ?? `nansen ${fullCommand}`,
3036
+ returns: researchCommand?.leaf?.returns,
3037
+ });
2880
3038
  result = filterFields(result, fields);
2881
3039
  }
2882
3040
 
2883
3041
  // Alerts list with --table uses custom table format
2884
3042
  if (command === 'alerts' && subcommand === 'list' && table) {
2885
3043
  output(formatAlertsTable(result));
2886
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
3044
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
2887
3045
  return { type: 'success', data: result };
2888
3046
  }
2889
3047
 
@@ -2894,14 +3052,14 @@ export async function runCLI(rawArgs, deps = {}) {
2894
3052
  if (streamOutput) {
2895
3053
  output(streamOutput);
2896
3054
  }
2897
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
3055
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
2898
3056
  return { type: 'stream', data: result };
2899
3057
  }
2900
3058
 
2901
3059
  const successData = { success: true, data: result };
2902
3060
  const formatted = formatOutput(successData, { pretty, table, csv });
2903
3061
  output(formatted.text);
2904
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
3062
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
2905
3063
  return { type: csv ? 'csv' : 'success', data: result };
2906
3064
  } catch (error) {
2907
3065
  // A failed later page can still have incurred charges on earlier pages.
@@ -2927,7 +3085,7 @@ export async function runCLI(rawArgs, deps = {}) {
2927
3085
  output(formatted.text);
2928
3086
  }
2929
3087
  await trackFailed({
2930
- command: fullCommand,
3088
+ command: telemetryCommand,
2931
3089
  duration_ms: Date.now() - startTime,
2932
3090
  error_code: error.code || 'UNKNOWN',
2933
3091
  status: error.status || null,