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
@@ -0,0 +1,555 @@
1
+ /**
2
+ * Nansen CLI - Shared input validation for research commands (API-1080, API-1081).
3
+ *
4
+ * One path checks every research command before it spends a request:
5
+ * - unknown commands and subcommands (with the closest match),
6
+ * - options the command does not accept (including flags it would ignore,
7
+ * such as --limit on an endpoint without pagination),
8
+ * - missing required options and options given without a value,
9
+ * - enum, number and date values,
10
+ * - chains the endpoint does not accept (src/api-endpoints.json).
11
+ *
12
+ * src/schema.json is the source of truth for what each command accepts, so
13
+ * `nansen schema` documents exactly what this module enforces.
14
+ *
15
+ * Every failure is a NansenError whose `details` mirrors the REST API's 422
16
+ * body: `param` names the first bad option and `errors[]` lists each one as
17
+ * { field, message, code } with the API's snake_case field codes. The wording
18
+ * lists valid fields/options for unknown names, as REST and MCP do.
19
+ */
20
+
21
+ import { NansenError, ErrorCode, SERVER_CODE_MAP } from './api.js';
22
+
23
+ // ============= Suggestions =============
24
+
25
+ /** Longest common block of a[alo:ahi] and b[blo:bhi], as [i, j, size]. */
26
+ function longestMatch(a, b, alo, ahi, blo, bhi) {
27
+ let best = [alo, blo, 0];
28
+ let lengths = new Map();
29
+ for (let i = alo; i < ahi; i++) {
30
+ const next = new Map();
31
+ for (let j = blo; j < bhi; j++) {
32
+ if (a[i] !== b[j]) continue;
33
+ const size = (lengths.get(j - 1) || 0) + 1;
34
+ next.set(j, size);
35
+ if (size > best[2]) best = [i - size + 1, j - size + 1, size];
36
+ }
37
+ lengths = next;
38
+ }
39
+ return best;
40
+ }
41
+
42
+ function matchingCharacters(a, b, alo, ahi, blo, bhi) {
43
+ const [i, j, size] = longestMatch(a, b, alo, ahi, blo, bhi);
44
+ if (size === 0) return 0;
45
+ return size
46
+ + matchingCharacters(a, b, alo, i, blo, j)
47
+ + matchingCharacters(a, b, i + size, ahi, j + size, bhi);
48
+ }
49
+
50
+ /**
51
+ * Similarity in [0, 1]: Python's difflib.SequenceMatcher(None, a, b).ratio().
52
+ * Used for command names and invalid values.
53
+ */
54
+ export function similarity(a, b) {
55
+ const total = a.length + b.length;
56
+ if (total === 0) return 1;
57
+ return (2 * matchingCharacters(a, b, 0, a.length, 0, b.length)) / total;
58
+ }
59
+
60
+ /**
61
+ * The candidate closest to `input` (case-insensitive), or null below `cutoff`.
62
+ * Like difflib.get_close_matches(n=1): highest score wins, and a tie goes to
63
+ * the candidate that sorts last.
64
+ */
65
+ export function closestMatch(input, candidates, cutoff = 0.6) {
66
+ const needle = String(input).toLowerCase();
67
+ let best = null;
68
+ let bestScore = -1;
69
+ for (const candidate of candidates) {
70
+ const lowered = String(candidate).toLowerCase();
71
+ // get_close_matches scores SequenceMatcher(None, candidate, word): the
72
+ // order matters, because ties in the longest match resolve differently.
73
+ const score = similarity(lowered, needle);
74
+ if (score < cutoff) continue;
75
+ if (score > bestScore || (score === bestScore && lowered > String(best).toLowerCase())) {
76
+ best = candidate;
77
+ bestScore = score;
78
+ }
79
+ }
80
+ return best;
81
+ }
82
+
83
+ /** 'a', 'b' or 'c' — the REST API's list wording. */
84
+ export function quotedList(values) {
85
+ const quoted = values.map(value => `'${value}'`);
86
+ if (quoted.length <= 1) return quoted.join('');
87
+ return `${quoted.slice(0, -1).join(', ')} or ${quoted[quoted.length - 1]}`;
88
+ }
89
+
90
+ // ============= Errors =============
91
+
92
+ export function fieldError(field, code, message) {
93
+ return { field, message, code };
94
+ }
95
+
96
+ /**
97
+ * One NansenError for a list of field errors. The first error leads, like the
98
+ * REST API's top-level message; every error stays in details.errors.
99
+ */
100
+ export function validationError(errors) {
101
+ const [first] = errors;
102
+ const code = SERVER_CODE_MAP[first.code] ?? ErrorCode.INVALID_PARAMS;
103
+ const more = errors.length > 1 ? ` (${errors.length - 1} more error${errors.length === 2 ? '' : 's'} in details.errors)` : '';
104
+ return new NansenError(`${first.message}${more}`, code, null, { param: first.field, errors });
105
+ }
106
+
107
+ /**
108
+ * UNKNOWN_COMMAND with the closest valid name, e.g.
109
+ * "Unknown token subcommand: scrrener. Did you mean 'screener'? Available: ...".
110
+ */
111
+ export function unknownCommandError(kind, name, available) {
112
+ const suggestion = closestMatch(name, available);
113
+ const hint = suggestion ? ` Did you mean '${suggestion}'?` : '';
114
+ return new NansenError(
115
+ `Unknown ${kind}: ${name}.${hint} Available: ${available.join(', ')}`,
116
+ ErrorCode.UNKNOWN_COMMAND,
117
+ null,
118
+ { available, ...(suggestion && { suggestion }) },
119
+ );
120
+ }
121
+
122
+ // ============= Command resolution =============
123
+
124
+ // Top-level shortcuts that resolve before routing (mirrors COMMAND_ALIASES in cli.js).
125
+ const CATEGORY_ALIASES = { tgm: 'token', sm: 'smart-money', prof: 'profiler', port: 'portfolio', pm: 'prediction-market' };
126
+ // Categories that still run without the `research` prefix.
127
+ const TOP_LEVEL_CATEGORIES = new Set(['smart-money', 'profiler', 'token', 'search', 'portfolio', 'prediction-market']);
128
+ // Subcommand spellings a handler accepts besides the schema name.
129
+ export const SUBCOMMAND_ALIASES = { portfolio: { 'defi-holdings': 'defi' } };
130
+ // Commands whose endpoint was removed. Their handler still answers with
131
+ // COMMAND_UNAVAILABLE, both as `nansen <name>` and `nansen research <name>`,
132
+ // but they are left out of the schema, help listings, completions and "did
133
+ // you mean" suggestions so agents do not spend a call on them. Validation
134
+ // skips them, since the schema no longer has an entry to check against.
135
+ export const UNAVAILABLE_COMMANDS = new Set(['points']);
136
+
137
+ /**
138
+ * The research schema entry a command line runs, or null when the command is
139
+ * not a research command (or asks for help). Throws UNKNOWN_COMMAND for a
140
+ * category or subcommand that does not exist.
141
+ *
142
+ * Returns { path, leaf, positional } where `positional` is the arguments after
143
+ * the subcommand.
144
+ */
145
+ export function resolveResearchCommand(schema, command, subArgs) {
146
+ const research = schema.commands.research.subcommands;
147
+ let category;
148
+ let rest;
149
+ let prefix;
150
+ if (command === 'research') {
151
+ const raw = subArgs[0];
152
+ if (!raw || raw === 'help') return null;
153
+ category = Object.hasOwn(CATEGORY_ALIASES, raw) ? CATEGORY_ALIASES[raw] : raw;
154
+ if (UNAVAILABLE_COMMANDS.has(category)) return null;
155
+ if (!Object.hasOwn(research, category)) {
156
+ throw unknownCommandError('research category', raw, Object.keys(research));
157
+ }
158
+ rest = subArgs.slice(1);
159
+ prefix = `research ${category}`;
160
+ } else if (command === 'perp' && (subArgs[0] === 'screener' || subArgs[0] === 'leaderboard')) {
161
+ category = 'perp';
162
+ rest = subArgs;
163
+ prefix = 'perp';
164
+ } else if (TOP_LEVEL_CATEGORIES.has(command)) {
165
+ category = command;
166
+ rest = subArgs;
167
+ prefix = command;
168
+ } else {
169
+ return null;
170
+ }
171
+
172
+ const entry = research[category];
173
+ if (!entry.subcommands) {
174
+ if (rest[0] === 'help') return null;
175
+ return { path: `nansen ${prefix}`, leaf: entry, positional: rest };
176
+ }
177
+ const rawSub = rest[0];
178
+ if (!rawSub || rawSub === 'help') return null;
179
+ const aliases = SUBCOMMAND_ALIASES[category] ?? {};
180
+ const sub = Object.hasOwn(aliases, rawSub) ? aliases[rawSub] : rawSub;
181
+ // Own properties only: `toString` or `constructor` is not a subcommand.
182
+ const leaf = Object.hasOwn(entry.subcommands, sub) ? entry.subcommands[sub] : null;
183
+ if (!leaf) {
184
+ throw unknownCommandError(`${category} subcommand`, rawSub, Object.keys(entry.subcommands));
185
+ }
186
+ if (rest[1] === 'help') return null;
187
+ return { path: `nansen ${prefix} ${sub}`, leaf, positional: rest.slice(1) };
188
+ }
189
+
190
+ // ============= Option validation =============
191
+
192
+ // Options every command accepts: output, caching, retries and debugging.
193
+ export const COMMON_OPTIONS = new Set([
194
+ 'help', 'h', 'version', 'v', 'pretty', 'p', 'table', 't', 'stream', 's', 'fields', 'format',
195
+ 'no-retry', 'retries', 'cache', 'no-cache', 'cache-ttl', 'debug', 'x402-payment-signature',
196
+ ]);
197
+ // Options that only make sense on a paginated endpoint.
198
+ export const PAGINATION_OPTIONS = new Set(['limit', 'page', 'paginate', 'all', 'max-pages']);
199
+ const PAGINATION_SPECS = {
200
+ limit: { type: 'integer', minimum: 1, description: 'Results per page' },
201
+ page: { type: 'integer', minimum: 1, description: 'Page number (1-based)' },
202
+ };
203
+
204
+ // The chain aliases the REST API accepts.
205
+ // The API folds case and maps these to the canonical name, so the CLI does
206
+ // the same before it checks the chain and sends the request.
207
+ export const CHAIN_ALIASES = {
208
+ bsc: 'bnb',
209
+ 'binance-smart-chain': 'bnb',
210
+ binance: 'bnb',
211
+ eth: 'ethereum',
212
+ sol: 'solana',
213
+ arb: 'arbitrum',
214
+ avax: 'avalanche',
215
+ poly: 'polygon',
216
+ op: 'optimism',
217
+ 'base-mainnet': 'base',
218
+ fantom: 'ftm',
219
+ };
220
+
221
+ /** The canonical spelling of a chain: lowercase, with REST's aliases applied. */
222
+ export function canonicalChain(value) {
223
+ if (typeof value !== 'string') return value;
224
+ const lowered = value.trim().toLowerCase();
225
+ return CHAIN_ALIASES[lowered] ?? lowered;
226
+ }
227
+
228
+ function isBlank(value) {
229
+ return value === true || (typeof value === 'string' && value.trim() === '');
230
+ }
231
+
232
+ function isValidDateOnly(value) {
233
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
234
+ const parsed = new Date(`${value}T00:00:00.000Z`);
235
+ return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
236
+ }
237
+
238
+ /** Map every accepted spelling (name and aliases) to its schema option name. */
239
+ function optionNames(leaf) {
240
+ const names = new Map();
241
+ for (const [name, spec] of Object.entries(leaf.options || {})) {
242
+ names.set(name, name);
243
+ for (const alias of spec.aliases || []) names.set(alias, name);
244
+ }
245
+ return names;
246
+ }
247
+
248
+ function splitList(value) {
249
+ if (Array.isArray(value)) return value.flatMap(splitList);
250
+ if (typeof value !== 'string') return [value];
251
+ return value.split(',').map(part => part.trim()).filter(Boolean);
252
+ }
253
+
254
+ /** Chains the command accepts for `option`, or null when unknown. */
255
+ export function supportedChains(leaf, option, endpoints) {
256
+ // The API spec is authoritative; a hand-written enum is only a fallback.
257
+ const endpoint = endpoints?.[leaf.endpoint];
258
+ if (endpoint?.chains?.length) return endpoint.chains;
259
+ const spec = leaf.options?.[option];
260
+ return Array.isArray(spec?.enum) && spec.enum.length ? spec.enum : null;
261
+ }
262
+
263
+ // Chain typos need a closer match than option names: at 0.6, 'bitcoin' would
264
+ // suggest 'ton'.
265
+ const CHAIN_SUGGESTION_CUTOFF = 0.75;
266
+
267
+ function chainSuggestion(chain, allowed, knownChains) {
268
+ // A real chain this command does not support is not a typo.
269
+ if (knownChains.has(chain)) return null;
270
+ return closestMatch(chain, allowed, CHAIN_SUGGESTION_CUTOFF);
271
+ }
272
+
273
+ function chainErrors(path, leaf, option, value, endpoints, knownChains) {
274
+ const items = splitList(value);
275
+ const errors = [];
276
+ // --chain names one chain. Only --chains takes a list; "eth,sol" here would be
277
+ // sent as a single, unresolvable chain name.
278
+ const raw = Array.isArray(value) ? value.join(',') : value;
279
+ if (option === 'chain' && typeof raw === 'string' && raw.includes(',')) {
280
+ const hint = leaf.options?.chains ? ' Use --chains for several chains.' : '';
281
+ errors.push(fieldError('--chain', 'invalid_field_value', `Option '--chain' takes one chain; received: ${raw}.${hint}`));
282
+ return errors;
283
+ }
284
+ const allowed = supportedChains(leaf, option, endpoints);
285
+ if (!allowed) return [];
286
+ for (const raw of items) {
287
+ if (typeof raw !== 'string') continue;
288
+ const chain = canonicalChain(raw);
289
+ if (allowed.includes(chain)) continue;
290
+ const suggestion = chainSuggestion(chain, allowed, knownChains);
291
+ const hint = suggestion ? ` Did you mean '${suggestion}'?` : '';
292
+ errors.push(fieldError(
293
+ `--${option}`,
294
+ 'invalid_field_value',
295
+ `Chain '${raw}' is not supported by ${path}.${hint} Supported chains: ${allowed.join(', ')}`,
296
+ ));
297
+ }
298
+ return errors;
299
+ }
300
+
301
+ /**
302
+ * Rewrite --chain/--chains to canonical spellings, as the API would. --chains
303
+ * becomes an array (the request field is a list), whether it was given as
304
+ * "a,b", repeated, or as a JSON array.
305
+ */
306
+ function normalizeChainOptions(options, names) {
307
+ for (const [raw, canonical] of names) {
308
+ if (canonical !== 'chain' && canonical !== 'chains') continue;
309
+ const value = options[raw];
310
+ if (canonical === 'chains' && (Array.isArray(value) || (typeof value === 'string' && value.trim() !== ''))) {
311
+ options[raw] = splitList(value).map(canonicalChain);
312
+ } else if (typeof value === 'string' && value.trim() !== '') {
313
+ options[raw] = canonicalChain(value);
314
+ }
315
+ }
316
+ }
317
+
318
+ function isValidDateTime(value) {
319
+ if (isValidDateOnly(value)) return true;
320
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?$/.test(value)) return false;
321
+ return isValidDateOnly(value.slice(0, 10)) && !Number.isNaN(Date.parse(value.replace(' ', 'T')));
322
+ }
323
+
324
+ function valueErrors(name, spec, value) {
325
+ const field = `--${name}`;
326
+ // A JSON option takes an array as its value (--order-by '[...]').
327
+ if (spec.format === 'json') return [];
328
+ // parseArgs turns a repeated option into an array, and so does a JSON
329
+ // array value. List options (`repeatable`) take either; others take one value.
330
+ if (Array.isArray(value) && !spec.repeatable) {
331
+ return [fieldError(field, 'invalid_field_value', `Option '${field}' may only be given once`)];
332
+ }
333
+ const values = Array.isArray(value) ? value : [value];
334
+ const errors = [];
335
+ for (const item of values) {
336
+ // parseArgs turns JSON-looking values into objects. Only JSON options
337
+ // take one; elsewhere it would be dropped and the default sent instead.
338
+ if (item !== null && typeof item === 'object') {
339
+ errors.push(fieldError(field, 'invalid_field_value', `Option '${field}' must be a ${spec.type === 'boolean' ? 'boolean' : spec.type === 'number' || spec.type === 'integer' ? 'number' : 'string'}, not JSON; received: ${JSON.stringify(item)}`));
340
+ continue;
341
+ }
342
+ if (spec.type === 'boolean') {
343
+ if (item === true) continue;
344
+ if (!['true', 'false', '1', '0'].includes(String(item).toLowerCase())) {
345
+ errors.push(fieldError(field, 'invalid_field_value', `Option '${field}' must be true or false`));
346
+ }
347
+ continue;
348
+ }
349
+ if (Array.isArray(spec.enum) && spec.enum.length && typeof item !== 'object') {
350
+ const text = String(item);
351
+ if (!spec.enum.some(option => String(option).toLowerCase() === text.toLowerCase())) {
352
+ const options = spec.enum.map(String);
353
+ const suggestion = closestMatch(text, options);
354
+ errors.push(fieldError(field, 'invalid_field_value', suggestion
355
+ ? `Invalid value '${text}' for ${field}. Did you mean '${suggestion}'? Valid options are: ${quotedList(options)}`
356
+ : `Invalid value '${text}' for ${field}. Valid options are: ${quotedList(options)}`));
357
+ continue;
358
+ }
359
+ }
360
+ if (spec.type === 'number' || spec.type === 'integer') {
361
+ const number = typeof item === 'string' && item.trim() !== '' ? Number(item) : (typeof item === 'number' ? item : NaN);
362
+ if (!Number.isFinite(number) || (spec.type === 'integer' && !Number.isSafeInteger(number))) {
363
+ errors.push(fieldError(field, 'invalid_field_value', `Option '${field}' must be ${spec.type === 'integer' ? 'a whole number' : 'a number'}; received: ${String(item)}`));
364
+ continue;
365
+ }
366
+ if (typeof spec.minimum === 'number' && number < spec.minimum) {
367
+ errors.push(fieldError(field, 'value_out_of_range', `Value for '${field}' is out of the allowed range (must be at least ${spec.minimum}); received: ${String(item)}`));
368
+ } else if (typeof spec.maximum === 'number' && number > spec.maximum) {
369
+ errors.push(fieldError(field, 'value_out_of_range', `Value for '${field}' is out of the allowed range (must be at most ${spec.maximum}); received: ${String(item)}`));
370
+ }
371
+ continue;
372
+ }
373
+ if (spec.format === 'date' && !isValidDateOnly(item)) {
374
+ errors.push(fieldError(field, 'invalid_date_format', `Invalid date '${String(item)}' for ${field}. Expected a real calendar date as YYYY-MM-DD.`));
375
+ } else if (spec.format === 'date-time' && !isValidDateTime(item)) {
376
+ errors.push(fieldError(field, 'invalid_date_format', `Invalid date '${String(item)}' for ${field}. Expected YYYY-MM-DD or an ISO 8601 time such as 2025-01-01T00:00:00Z.`));
377
+ }
378
+ }
379
+ return errors;
380
+ }
381
+
382
+ /**
383
+ * Check a research command's options before it runs. Throws one NansenError
384
+ * listing every problem (see validationError). On success it rewrites
385
+ * --chain/--chains in `options` to their canonical spelling (lowercase, REST
386
+ * aliases such as bsc -> bnb applied), as the API itself would, and turns
387
+ * --chains into an array.
388
+ */
389
+ export function validateResearchInput(resolved, { flags = {}, options = {}, endpoints = {}, chains = [] } = {}) {
390
+ const { path, leaf, positional = [] } = resolved;
391
+ const names = optionNames(leaf);
392
+ const pagination = leaf.pagination !== false;
393
+ const errors = [];
394
+ const given = new Map(); // schema name -> raw value
395
+ const accepted = [...names.keys()].filter(name => names.get(name) === name);
396
+ const visible = [...new Set([...accepted, ...(pagination ? PAGINATION_OPTIONS : [])])].map(name => `--${name}`);
397
+
398
+ const supplied = [
399
+ ...Object.entries(options).map(([name, value]) => [name, value]),
400
+ ...Object.entries(flags).filter(([name, value]) => value && !(name in options)).map(([name, value]) => [name, value]),
401
+ ];
402
+ for (const [raw, value] of supplied) {
403
+ const canonical = names.get(raw);
404
+ if (canonical) {
405
+ given.set(canonical, value);
406
+ continue;
407
+ }
408
+ if (COMMON_OPTIONS.has(raw)) continue;
409
+ if (PAGINATION_OPTIONS.has(raw)) {
410
+ if (pagination) {
411
+ if (PAGINATION_SPECS[raw]) given.set(raw, value);
412
+ continue;
413
+ }
414
+ errors.push(fieldError(`--${raw}`, 'unknown_field', `Option '--${raw}' is not supported by ${path}: this endpoint does not paginate.`));
415
+ continue;
416
+ }
417
+ const field = raw.length === 1 ? `-${raw}` : `--${raw}`;
418
+ errors.push(fieldError(field, 'unknown_field',
419
+ `Option '${field}' is not recognized by ${path}. Command-specific options: ${visible.join(', ') || 'none'}. Common options also apply; see: nansen schema.`));
420
+ }
421
+
422
+ for (const [name, value] of given) {
423
+ const spec = leaf.options?.[name] ?? PAGINATION_SPECS[name];
424
+ if (!spec) continue;
425
+ // A list option needs at least one item: `--chains ,` would send [].
426
+ if (spec.type !== 'boolean' && (isBlank(value) || (spec.repeatable && spec.format !== 'json' && splitList(value).length === 0))) {
427
+ errors.push(fieldError(`--${name}`, 'missing_field', `Option '--${name}' requires a value.`));
428
+ continue;
429
+ }
430
+ errors.push(...valueErrors(name, spec, value));
431
+ }
432
+
433
+ for (const [name, spec] of Object.entries(leaf.options || {})) {
434
+ if (!spec.required || given.has(name)) continue;
435
+ if (spec.positional && positional.length > 0) continue;
436
+ if ((spec.requiredUnless || []).some(other => given.has(other))) continue;
437
+ const alternatives = (spec.requiredUnless || []).map(other => `--${other}`);
438
+ errors.push(fieldError(`--${name}`, 'missing_field', alternatives.length
439
+ ? `Required option '--${name}' is missing (or pass ${alternatives.join(' or ')}).`
440
+ : `Required option '--${name}' is missing.`));
441
+ }
442
+
443
+ const knownChains = new Set(chains);
444
+ for (const option of ['chain', 'chains']) {
445
+ if (!given.has(option) || isBlank(given.get(option))) continue;
446
+ errors.push(...chainErrors(path, leaf, option, given.get(option), endpoints, knownChains));
447
+ }
448
+
449
+ if (errors.length) throw validationError(errors);
450
+ normalizeChainOptions(options, names);
451
+ }
452
+
453
+ /** Reject an output format the CLI cannot write. */
454
+ export function validateOutputOptions({ flags = {}, options = {} } = {}) {
455
+ // --fields is applied after the response arrives; check its shape here so
456
+ // a bad value fails before the (billed) request instead of after it.
457
+ if (flags.fields === true || (typeof options.fields === 'string' && options.fields.split(',').every(f => f.trim() === ''))) {
458
+ throw validationError([fieldError('--fields', 'missing_field', "Option '--fields' requires a value. Usage: --fields name,value_usd")]);
459
+ }
460
+ if (options.fields !== undefined && typeof options.fields !== 'string') {
461
+ throw validationError([fieldError('--fields', 'invalid_field_value', "Option '--fields' takes one comma-separated list. Usage: --fields name,value_usd")]);
462
+ }
463
+ if (flags.format === true || (typeof options.format === 'string' && options.format.trim() === '')) {
464
+ throw validationError([fieldError('--format', 'missing_field', "Option '--format' requires a value. Valid options are: 'json' or 'csv'")]);
465
+ }
466
+ if (options.format === undefined) return;
467
+ const valid = ['json', 'csv'];
468
+ if (typeof options.format !== 'string' || !valid.includes(options.format)) {
469
+ const text = typeof options.format === 'string' ? options.format : JSON.stringify(options.format);
470
+ const suggestion = closestMatch(text, valid);
471
+ throw validationError([fieldError('--format', 'invalid_field_value', suggestion
472
+ ? `Invalid value '${text}' for --format. Did you mean '${suggestion}'? Valid options are: ${quotedList(valid)}`
473
+ : `Invalid value '${text}' for --format. Valid options are: ${quotedList(valid)}`)]);
474
+ }
475
+ }
476
+
477
+ // ============= --fields =============
478
+
479
+ /** Every key, and every key path counted from the root, in a response payload. */
480
+ function collectKeys(data) {
481
+ const names = new Set();
482
+ const paths = new Set();
483
+ let arrays = 0;
484
+ let rows = 0;
485
+ (function walk(node, path, depth) {
486
+ if (depth > 12 || node === null || typeof node !== 'object') return;
487
+ if (Array.isArray(node)) {
488
+ arrays++;
489
+ // Every row: an optional field may appear only on a late row, and
490
+ // filterFields() looks at all of them too.
491
+ for (const item of node) {
492
+ if (item !== null && typeof item === 'object') rows++;
493
+ walk(item, path, depth + 1);
494
+ }
495
+ return;
496
+ }
497
+ for (const [key, value] of Object.entries(node)) {
498
+ const keyPath = path ? `${path}.${key}` : key;
499
+ names.add(key);
500
+ paths.add(keyPath);
501
+ walk(value, keyPath, depth + 1);
502
+ }
503
+ })(data, '', 0);
504
+ // Lists that are all empty: the row fields are unknown, not absent.
505
+ return { names, paths, empty: arrays > 0 && rows === 0 };
506
+ }
507
+
508
+ /**
509
+ * Reject --fields names that match nothing. A name is known when the response
510
+ * has that key at any depth (a dotted path must exist at exactly that
511
+ * position, as filterFields() requires), or
512
+ * when the command's schema lists it in `returns`. An empty response (no
513
+ * rows) is never rejected: it cannot show which fields exist.
514
+ */
515
+ export function validateFieldSelection(data, fields, { path, returns = [] } = {}) {
516
+ if (!fields?.length) return;
517
+ const { names, paths, empty } = collectKeys(data);
518
+ const documented = new Set(returns);
519
+ // With no rows there is nothing to compare against, and a schema `returns`
520
+ // list may be incomplete, so an empty result never fails here.
521
+ if (empty || names.size === 0) return;
522
+ const candidates = [...new Set([...names, ...documented])].filter(name => !name.startsWith('_'));
523
+ const fieldList = candidates.length > 40
524
+ ? `Available fields (first 40 of ${candidates.length}): ${candidates.slice(0, 40).join(', ')}. Run without --fields to inspect the full response; see nansen schema for documented fields.`
525
+ : `Available fields: ${candidates.join(', ')}`;
526
+ const errors = [];
527
+ for (const field of fields) {
528
+ const known = field.includes('.')
529
+ ? paths.has(field) || documented.has(field)
530
+ : names.has(field) || documented.has(field);
531
+ if (known) continue;
532
+ const where = path ? ` from ${path}` : '';
533
+ errors.push(fieldError('--fields', 'unknown_field', `Field '${field}' is not in the response${where}. ${fieldList}`));
534
+ }
535
+ if (errors.length) throw validationError(errors);
536
+ }
537
+
538
+ // ============= Filters =============
539
+
540
+ const EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
541
+
542
+ /**
543
+ * Lowercase every EVM address (0x + 40 hex) inside a filters object. The API
544
+ * stores EVM addresses lowercase, so a checksummed address in a filter
545
+ * matched nothing and returned an empty success. Other address formats
546
+ * (Solana, Tron, TON, ...) are case-sensitive and never match the pattern.
547
+ */
548
+ export function normalizeFilterAddresses(value) {
549
+ if (typeof value === 'string') return EVM_ADDRESS.test(value) ? value.toLowerCase() : value;
550
+ if (Array.isArray(value)) return value.map(normalizeFilterAddresses);
551
+ if (value && typeof value === 'object') {
552
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalizeFilterAddresses(item)]));
553
+ }
554
+ return value;
555
+ }