nansen-cli 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +109 -33
  3. package/docs/auth.md +56 -0
  4. package/docs/browser-login.md +101 -7
  5. package/docs/error-codes.md +249 -0
  6. package/package.json +10 -4
  7. package/skills/nansen-agent-guide/SKILL.md +54 -1
  8. package/skills/nansen-alerts-webhook-listener/SKILL.md +1 -1
  9. package/skills/nansen-dca-tracker/SKILL.md +1 -1
  10. package/skills/nansen-defi-positions/SKILL.md +1 -1
  11. package/skills/nansen-exit-signals/SKILL.md +2 -2
  12. package/skills/nansen-fund-tracker/SKILL.md +1 -1
  13. package/skills/nansen-general-search/SKILL.md +1 -1
  14. package/skills/nansen-holder-analysis/SKILL.md +2 -2
  15. package/skills/nansen-limit-orders/SKILL.md +1 -1
  16. package/skills/nansen-mpp-payment/SKILL.md +2 -2
  17. package/skills/nansen-perp-screener/SKILL.md +1 -1
  18. package/skills/nansen-perp-trader-profile/SKILL.md +1 -1
  19. package/skills/nansen-polymarket-deep-dive/SKILL.md +1 -1
  20. package/skills/nansen-polymarket-insider-scan/SKILL.md +1 -1
  21. package/skills/nansen-polymarket-trader-profile/SKILL.md +1 -1
  22. package/skills/nansen-portfolio-tracker/SKILL.md +1 -1
  23. package/skills/nansen-prediction-markets/SKILL.md +1 -1
  24. package/skills/nansen-sm-cross-chain-flows/SKILL.md +1 -1
  25. package/skills/nansen-smart-alerts/SKILL.md +2 -1
  26. package/skills/nansen-smart-money-alpha/SKILL.md +1 -1
  27. package/skills/nansen-smart-money-tracker/SKILL.md +8 -7
  28. package/skills/nansen-smart-money-trend/SKILL.md +1 -1
  29. package/skills/nansen-token-research/SKILL.md +1 -1
  30. package/skills/nansen-token-screener/SKILL.md +1 -1
  31. package/skills/nansen-token-transfer-analysis/SKILL.md +1 -1
  32. package/skills/nansen-trading/SKILL.md +1 -1
  33. package/skills/nansen-wallet-batch/SKILL.md +1 -1
  34. package/skills/nansen-wallet-clustering/SKILL.md +1 -1
  35. package/skills/nansen-wallet-deep-dive/SKILL.md +1 -1
  36. package/skills/nansen-wallet-keychain-migration/SKILL.md +1 -1
  37. package/skills/nansen-wallet-manager/SKILL.md +1 -1
  38. package/skills/nansen-wallet-profiler/SKILL.md +1 -1
  39. package/skills/nansen-web-fetcher/SKILL.md +1 -1
  40. package/skills/nansen-web-searcher/SKILL.md +1 -1
  41. package/src/api-endpoints.json +1605 -0
  42. package/src/api.js +336 -121
  43. package/src/auth-credentials.js +1 -0
  44. package/src/auth-state.js +2 -2
  45. package/src/auth-store-native.js +6 -1
  46. package/src/auth-store-worker.js +1 -1
  47. package/src/auth-store.js +9 -4
  48. package/src/bridge.js +19 -10
  49. package/src/cli.js +258 -107
  50. package/src/commands/agent.js +2 -3
  51. package/src/commands/alerts.js +277 -9
  52. package/src/commands/completion.js +6 -1
  53. package/src/commands/feedback.js +413 -0
  54. package/src/commands/mcp.js +1 -1
  55. package/src/commands/research.js +14 -37
  56. package/src/cost-cache.js +33 -7
  57. package/src/doctor.js +14 -5
  58. package/src/error-codes.js +226 -0
  59. package/src/feedback-journal.js +86 -0
  60. package/src/input-validation.js +551 -0
  61. package/src/limit-order.js +12 -3
  62. package/src/perp.js +2 -1
  63. package/src/privy.js +144 -48
  64. package/src/query-options.js +30 -7
  65. package/src/rpc-urls.js +3 -1
  66. package/src/schema.json +1254 -150
  67. package/src/solana-tx.js +4 -0
  68. package/src/telemetry.js +5 -1
  69. package/src/trade-validation.js +190 -21
  70. package/src/trading.js +229 -129
  71. package/src/transfer.js +7 -1
  72. package/src/update-check.js +32 -5
  73. package/src/wallet.js +220 -57
  74. package/src/walletconnect-x402.js +152 -52
  75. package/src/x402-audit.js +191 -0
  76. package/src/x402-payment-balance.js +90 -0
  77. package/src/x402-policy.js +151 -4
  78. package/src/x402.js +51 -22
@@ -0,0 +1,551 @@
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
+ const SUBCOMMAND_ALIASES = { portfolio: { 'defi-holdings': 'defi' } };
130
+ // Categories whose handler does its own routing and never calls the API.
131
+ const UNVALIDATED_CATEGORIES = new Set(['points']);
132
+
133
+ /**
134
+ * The research schema entry a command line runs, or null when the command is
135
+ * not a research command (or asks for help). Throws UNKNOWN_COMMAND for a
136
+ * category or subcommand that does not exist.
137
+ *
138
+ * Returns { path, leaf, positional } where `positional` is the arguments after
139
+ * the subcommand.
140
+ */
141
+ export function resolveResearchCommand(schema, command, subArgs) {
142
+ const research = schema.commands.research.subcommands;
143
+ let category;
144
+ let rest;
145
+ let prefix;
146
+ if (command === 'research') {
147
+ const raw = subArgs[0];
148
+ if (!raw || raw === 'help') return null;
149
+ category = Object.hasOwn(CATEGORY_ALIASES, raw) ? CATEGORY_ALIASES[raw] : raw;
150
+ if (!Object.hasOwn(research, category)) {
151
+ throw unknownCommandError('research category', raw, Object.keys(research));
152
+ }
153
+ rest = subArgs.slice(1);
154
+ prefix = `research ${category}`;
155
+ } else if (command === 'perp' && (subArgs[0] === 'screener' || subArgs[0] === 'leaderboard')) {
156
+ category = 'perp';
157
+ rest = subArgs;
158
+ prefix = 'perp';
159
+ } else if (TOP_LEVEL_CATEGORIES.has(command)) {
160
+ category = command;
161
+ rest = subArgs;
162
+ prefix = command;
163
+ } else {
164
+ return null;
165
+ }
166
+ if (UNVALIDATED_CATEGORIES.has(category)) return null;
167
+
168
+ const entry = research[category];
169
+ if (!entry.subcommands) {
170
+ if (rest[0] === 'help') return null;
171
+ return { path: `nansen ${prefix}`, leaf: entry, positional: rest };
172
+ }
173
+ const rawSub = rest[0];
174
+ if (!rawSub || rawSub === 'help') return null;
175
+ const aliases = SUBCOMMAND_ALIASES[category] ?? {};
176
+ const sub = Object.hasOwn(aliases, rawSub) ? aliases[rawSub] : rawSub;
177
+ // Own properties only: `toString` or `constructor` is not a subcommand.
178
+ const leaf = Object.hasOwn(entry.subcommands, sub) ? entry.subcommands[sub] : null;
179
+ if (!leaf) {
180
+ throw unknownCommandError(`${category} subcommand`, rawSub, Object.keys(entry.subcommands));
181
+ }
182
+ if (rest[1] === 'help') return null;
183
+ return { path: `nansen ${prefix} ${sub}`, leaf, positional: rest.slice(1) };
184
+ }
185
+
186
+ // ============= Option validation =============
187
+
188
+ // Options every command accepts: output, caching, retries and debugging.
189
+ export const COMMON_OPTIONS = new Set([
190
+ 'help', 'h', 'version', 'v', 'pretty', 'p', 'table', 't', 'stream', 's', 'fields', 'format',
191
+ 'no-retry', 'retries', 'cache', 'no-cache', 'cache-ttl', 'debug', 'x402-payment-signature',
192
+ ]);
193
+ // Options that only make sense on a paginated endpoint.
194
+ export const PAGINATION_OPTIONS = new Set(['limit', 'page', 'paginate', 'all', 'max-pages']);
195
+ const PAGINATION_SPECS = {
196
+ limit: { type: 'integer', minimum: 1, description: 'Results per page' },
197
+ page: { type: 'integer', minimum: 1, description: 'Page number (1-based)' },
198
+ };
199
+
200
+ // The chain aliases the REST API accepts.
201
+ // The API folds case and maps these to the canonical name, so the CLI does
202
+ // the same before it checks the chain and sends the request.
203
+ export const CHAIN_ALIASES = {
204
+ bsc: 'bnb',
205
+ 'binance-smart-chain': 'bnb',
206
+ binance: 'bnb',
207
+ eth: 'ethereum',
208
+ sol: 'solana',
209
+ arb: 'arbitrum',
210
+ avax: 'avalanche',
211
+ poly: 'polygon',
212
+ op: 'optimism',
213
+ 'base-mainnet': 'base',
214
+ fantom: 'ftm',
215
+ };
216
+
217
+ /** The canonical spelling of a chain: lowercase, with REST's aliases applied. */
218
+ export function canonicalChain(value) {
219
+ if (typeof value !== 'string') return value;
220
+ const lowered = value.trim().toLowerCase();
221
+ return CHAIN_ALIASES[lowered] ?? lowered;
222
+ }
223
+
224
+ function isBlank(value) {
225
+ return value === true || (typeof value === 'string' && value.trim() === '');
226
+ }
227
+
228
+ function isValidDateOnly(value) {
229
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
230
+ const parsed = new Date(`${value}T00:00:00.000Z`);
231
+ return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
232
+ }
233
+
234
+ /** Map every accepted spelling (name and aliases) to its schema option name. */
235
+ function optionNames(leaf) {
236
+ const names = new Map();
237
+ for (const [name, spec] of Object.entries(leaf.options || {})) {
238
+ names.set(name, name);
239
+ for (const alias of spec.aliases || []) names.set(alias, name);
240
+ }
241
+ return names;
242
+ }
243
+
244
+ function splitList(value) {
245
+ if (Array.isArray(value)) return value.flatMap(splitList);
246
+ if (typeof value !== 'string') return [value];
247
+ return value.split(',').map(part => part.trim()).filter(Boolean);
248
+ }
249
+
250
+ /** Chains the command accepts for `option`, or null when unknown. */
251
+ export function supportedChains(leaf, option, endpoints) {
252
+ // The API spec is authoritative; a hand-written enum is only a fallback.
253
+ const endpoint = endpoints?.[leaf.endpoint];
254
+ if (endpoint?.chains?.length) return endpoint.chains;
255
+ const spec = leaf.options?.[option];
256
+ return Array.isArray(spec?.enum) && spec.enum.length ? spec.enum : null;
257
+ }
258
+
259
+ // Chain typos need a closer match than option names: at 0.6, 'bitcoin' would
260
+ // suggest 'ton'.
261
+ const CHAIN_SUGGESTION_CUTOFF = 0.75;
262
+
263
+ function chainSuggestion(chain, allowed, knownChains) {
264
+ // A real chain this command does not support is not a typo.
265
+ if (knownChains.has(chain)) return null;
266
+ return closestMatch(chain, allowed, CHAIN_SUGGESTION_CUTOFF);
267
+ }
268
+
269
+ function chainErrors(path, leaf, option, value, endpoints, knownChains) {
270
+ const items = splitList(value);
271
+ const errors = [];
272
+ // --chain names one chain. Only --chains takes a list; "eth,sol" here would be
273
+ // sent as a single, unresolvable chain name.
274
+ const raw = Array.isArray(value) ? value.join(',') : value;
275
+ if (option === 'chain' && typeof raw === 'string' && raw.includes(',')) {
276
+ const hint = leaf.options?.chains ? ' Use --chains for several chains.' : '';
277
+ errors.push(fieldError('--chain', 'invalid_field_value', `Option '--chain' takes one chain; received: ${raw}.${hint}`));
278
+ return errors;
279
+ }
280
+ const allowed = supportedChains(leaf, option, endpoints);
281
+ if (!allowed) return [];
282
+ for (const raw of items) {
283
+ if (typeof raw !== 'string') continue;
284
+ const chain = canonicalChain(raw);
285
+ if (allowed.includes(chain)) continue;
286
+ const suggestion = chainSuggestion(chain, allowed, knownChains);
287
+ const hint = suggestion ? ` Did you mean '${suggestion}'?` : '';
288
+ errors.push(fieldError(
289
+ `--${option}`,
290
+ 'invalid_field_value',
291
+ `Chain '${raw}' is not supported by ${path}.${hint} Supported chains: ${allowed.join(', ')}`,
292
+ ));
293
+ }
294
+ return errors;
295
+ }
296
+
297
+ /**
298
+ * Rewrite --chain/--chains to canonical spellings, as the API would. --chains
299
+ * becomes an array (the request field is a list), whether it was given as
300
+ * "a,b", repeated, or as a JSON array.
301
+ */
302
+ function normalizeChainOptions(options, names) {
303
+ for (const [raw, canonical] of names) {
304
+ if (canonical !== 'chain' && canonical !== 'chains') continue;
305
+ const value = options[raw];
306
+ if (canonical === 'chains' && (Array.isArray(value) || (typeof value === 'string' && value.trim() !== ''))) {
307
+ options[raw] = splitList(value).map(canonicalChain);
308
+ } else if (typeof value === 'string' && value.trim() !== '') {
309
+ options[raw] = canonicalChain(value);
310
+ }
311
+ }
312
+ }
313
+
314
+ function isValidDateTime(value) {
315
+ if (isValidDateOnly(value)) return true;
316
+ 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;
317
+ return isValidDateOnly(value.slice(0, 10)) && !Number.isNaN(Date.parse(value.replace(' ', 'T')));
318
+ }
319
+
320
+ function valueErrors(name, spec, value) {
321
+ const field = `--${name}`;
322
+ // A JSON option takes an array as its value (--order-by '[...]').
323
+ if (spec.format === 'json') return [];
324
+ // parseArgs turns a repeated option into an array, and so does a JSON
325
+ // array value. List options (`repeatable`) take either; others take one value.
326
+ if (Array.isArray(value) && !spec.repeatable) {
327
+ return [fieldError(field, 'invalid_field_value', `Option '${field}' may only be given once`)];
328
+ }
329
+ const values = Array.isArray(value) ? value : [value];
330
+ const errors = [];
331
+ for (const item of values) {
332
+ // parseArgs turns JSON-looking values into objects. Only JSON options
333
+ // take one; elsewhere it would be dropped and the default sent instead.
334
+ if (item !== null && typeof item === 'object') {
335
+ 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)}`));
336
+ continue;
337
+ }
338
+ if (spec.type === 'boolean') {
339
+ if (item === true) continue;
340
+ if (!['true', 'false', '1', '0'].includes(String(item).toLowerCase())) {
341
+ errors.push(fieldError(field, 'invalid_field_value', `Option '${field}' must be true or false`));
342
+ }
343
+ continue;
344
+ }
345
+ if (Array.isArray(spec.enum) && spec.enum.length && typeof item !== 'object') {
346
+ const text = String(item);
347
+ if (!spec.enum.some(option => String(option).toLowerCase() === text.toLowerCase())) {
348
+ const options = spec.enum.map(String);
349
+ const suggestion = closestMatch(text, options);
350
+ errors.push(fieldError(field, 'invalid_field_value', suggestion
351
+ ? `Invalid value '${text}' for ${field}. Did you mean '${suggestion}'? Valid options are: ${quotedList(options)}`
352
+ : `Invalid value '${text}' for ${field}. Valid options are: ${quotedList(options)}`));
353
+ continue;
354
+ }
355
+ }
356
+ if (spec.type === 'number' || spec.type === 'integer') {
357
+ const number = typeof item === 'string' && item.trim() !== '' ? Number(item) : (typeof item === 'number' ? item : NaN);
358
+ if (!Number.isFinite(number) || (spec.type === 'integer' && !Number.isSafeInteger(number))) {
359
+ errors.push(fieldError(field, 'invalid_field_value', `Option '${field}' must be ${spec.type === 'integer' ? 'a whole number' : 'a number'}; received: ${String(item)}`));
360
+ continue;
361
+ }
362
+ if (typeof spec.minimum === 'number' && number < spec.minimum) {
363
+ 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)}`));
364
+ } else if (typeof spec.maximum === 'number' && number > spec.maximum) {
365
+ 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)}`));
366
+ }
367
+ continue;
368
+ }
369
+ if (spec.format === 'date' && !isValidDateOnly(item)) {
370
+ errors.push(fieldError(field, 'invalid_date_format', `Invalid date '${String(item)}' for ${field}. Expected a real calendar date as YYYY-MM-DD.`));
371
+ } else if (spec.format === 'date-time' && !isValidDateTime(item)) {
372
+ 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.`));
373
+ }
374
+ }
375
+ return errors;
376
+ }
377
+
378
+ /**
379
+ * Check a research command's options before it runs. Throws one NansenError
380
+ * listing every problem (see validationError). On success it rewrites
381
+ * --chain/--chains in `options` to their canonical spelling (lowercase, REST
382
+ * aliases such as bsc -> bnb applied), as the API itself would, and turns
383
+ * --chains into an array.
384
+ */
385
+ export function validateResearchInput(resolved, { flags = {}, options = {}, endpoints = {}, chains = [] } = {}) {
386
+ const { path, leaf, positional = [] } = resolved;
387
+ const names = optionNames(leaf);
388
+ const pagination = leaf.pagination !== false;
389
+ const errors = [];
390
+ const given = new Map(); // schema name -> raw value
391
+ const accepted = [...names.keys()].filter(name => names.get(name) === name);
392
+ const visible = [...new Set([...accepted, ...(pagination ? PAGINATION_OPTIONS : [])])].map(name => `--${name}`);
393
+
394
+ const supplied = [
395
+ ...Object.entries(options).map(([name, value]) => [name, value]),
396
+ ...Object.entries(flags).filter(([name, value]) => value && !(name in options)).map(([name, value]) => [name, value]),
397
+ ];
398
+ for (const [raw, value] of supplied) {
399
+ const canonical = names.get(raw);
400
+ if (canonical) {
401
+ given.set(canonical, value);
402
+ continue;
403
+ }
404
+ if (COMMON_OPTIONS.has(raw)) continue;
405
+ if (PAGINATION_OPTIONS.has(raw)) {
406
+ if (pagination) {
407
+ if (PAGINATION_SPECS[raw]) given.set(raw, value);
408
+ continue;
409
+ }
410
+ errors.push(fieldError(`--${raw}`, 'unknown_field', `Option '--${raw}' is not supported by ${path}: this endpoint does not paginate.`));
411
+ continue;
412
+ }
413
+ const field = raw.length === 1 ? `-${raw}` : `--${raw}`;
414
+ errors.push(fieldError(field, 'unknown_field',
415
+ `Option '${field}' is not recognized by ${path}. Command-specific options: ${visible.join(', ') || 'none'}. Common options also apply; see: nansen schema.`));
416
+ }
417
+
418
+ for (const [name, value] of given) {
419
+ const spec = leaf.options?.[name] ?? PAGINATION_SPECS[name];
420
+ if (!spec) continue;
421
+ // A list option needs at least one item: `--chains ,` would send [].
422
+ if (spec.type !== 'boolean' && (isBlank(value) || (spec.repeatable && spec.format !== 'json' && splitList(value).length === 0))) {
423
+ errors.push(fieldError(`--${name}`, 'missing_field', `Option '--${name}' requires a value.`));
424
+ continue;
425
+ }
426
+ errors.push(...valueErrors(name, spec, value));
427
+ }
428
+
429
+ for (const [name, spec] of Object.entries(leaf.options || {})) {
430
+ if (!spec.required || given.has(name)) continue;
431
+ if (spec.positional && positional.length > 0) continue;
432
+ if ((spec.requiredUnless || []).some(other => given.has(other))) continue;
433
+ const alternatives = (spec.requiredUnless || []).map(other => `--${other}`);
434
+ errors.push(fieldError(`--${name}`, 'missing_field', alternatives.length
435
+ ? `Required option '--${name}' is missing (or pass ${alternatives.join(' or ')}).`
436
+ : `Required option '--${name}' is missing.`));
437
+ }
438
+
439
+ const knownChains = new Set(chains);
440
+ for (const option of ['chain', 'chains']) {
441
+ if (!given.has(option) || isBlank(given.get(option))) continue;
442
+ errors.push(...chainErrors(path, leaf, option, given.get(option), endpoints, knownChains));
443
+ }
444
+
445
+ if (errors.length) throw validationError(errors);
446
+ normalizeChainOptions(options, names);
447
+ }
448
+
449
+ /** Reject an output format the CLI cannot write. */
450
+ export function validateOutputOptions({ flags = {}, options = {} } = {}) {
451
+ // --fields is applied after the response arrives; check its shape here so
452
+ // a bad value fails before the (billed) request instead of after it.
453
+ if (flags.fields === true || (typeof options.fields === 'string' && options.fields.split(',').every(f => f.trim() === ''))) {
454
+ throw validationError([fieldError('--fields', 'missing_field', "Option '--fields' requires a value. Usage: --fields name,value_usd")]);
455
+ }
456
+ if (options.fields !== undefined && typeof options.fields !== 'string') {
457
+ throw validationError([fieldError('--fields', 'invalid_field_value', "Option '--fields' takes one comma-separated list. Usage: --fields name,value_usd")]);
458
+ }
459
+ if (flags.format === true || (typeof options.format === 'string' && options.format.trim() === '')) {
460
+ throw validationError([fieldError('--format', 'missing_field', "Option '--format' requires a value. Valid options are: 'json' or 'csv'")]);
461
+ }
462
+ if (options.format === undefined) return;
463
+ const valid = ['json', 'csv'];
464
+ if (typeof options.format !== 'string' || !valid.includes(options.format)) {
465
+ const text = typeof options.format === 'string' ? options.format : JSON.stringify(options.format);
466
+ const suggestion = closestMatch(text, valid);
467
+ throw validationError([fieldError('--format', 'invalid_field_value', suggestion
468
+ ? `Invalid value '${text}' for --format. Did you mean '${suggestion}'? Valid options are: ${quotedList(valid)}`
469
+ : `Invalid value '${text}' for --format. Valid options are: ${quotedList(valid)}`)]);
470
+ }
471
+ }
472
+
473
+ // ============= --fields =============
474
+
475
+ /** Every key, and every key path counted from the root, in a response payload. */
476
+ function collectKeys(data) {
477
+ const names = new Set();
478
+ const paths = new Set();
479
+ let arrays = 0;
480
+ let rows = 0;
481
+ (function walk(node, path, depth) {
482
+ if (depth > 12 || node === null || typeof node !== 'object') return;
483
+ if (Array.isArray(node)) {
484
+ arrays++;
485
+ // Every row: an optional field may appear only on a late row, and
486
+ // filterFields() looks at all of them too.
487
+ for (const item of node) {
488
+ if (item !== null && typeof item === 'object') rows++;
489
+ walk(item, path, depth + 1);
490
+ }
491
+ return;
492
+ }
493
+ for (const [key, value] of Object.entries(node)) {
494
+ const keyPath = path ? `${path}.${key}` : key;
495
+ names.add(key);
496
+ paths.add(keyPath);
497
+ walk(value, keyPath, depth + 1);
498
+ }
499
+ })(data, '', 0);
500
+ // Lists that are all empty: the row fields are unknown, not absent.
501
+ return { names, paths, empty: arrays > 0 && rows === 0 };
502
+ }
503
+
504
+ /**
505
+ * Reject --fields names that match nothing. A name is known when the response
506
+ * has that key at any depth (a dotted path must exist at exactly that
507
+ * position, as filterFields() requires), or
508
+ * when the command's schema lists it in `returns`. An empty response (no
509
+ * rows) is never rejected: it cannot show which fields exist.
510
+ */
511
+ export function validateFieldSelection(data, fields, { path, returns = [] } = {}) {
512
+ if (!fields?.length) return;
513
+ const { names, paths, empty } = collectKeys(data);
514
+ const documented = new Set(returns);
515
+ // With no rows there is nothing to compare against, and a schema `returns`
516
+ // list may be incomplete, so an empty result never fails here.
517
+ if (empty || names.size === 0) return;
518
+ const candidates = [...new Set([...names, ...documented])].filter(name => !name.startsWith('_'));
519
+ const fieldList = candidates.length > 40
520
+ ? `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.`
521
+ : `Available fields: ${candidates.join(', ')}`;
522
+ const errors = [];
523
+ for (const field of fields) {
524
+ const known = field.includes('.')
525
+ ? paths.has(field) || documented.has(field)
526
+ : names.has(field) || documented.has(field);
527
+ if (known) continue;
528
+ const where = path ? ` from ${path}` : '';
529
+ errors.push(fieldError('--fields', 'unknown_field', `Field '${field}' is not in the response${where}. ${fieldList}`));
530
+ }
531
+ if (errors.length) throw validationError(errors);
532
+ }
533
+
534
+ // ============= Filters =============
535
+
536
+ const EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
537
+
538
+ /**
539
+ * Lowercase every EVM address (0x + 40 hex) inside a filters object. The API
540
+ * stores EVM addresses lowercase, so a checksummed address in a filter
541
+ * matched nothing and returned an empty success. Other address formats
542
+ * (Solana, Tron, TON, ...) are case-sensitive and never match the pattern.
543
+ */
544
+ export function normalizeFilterAddresses(value) {
545
+ if (typeof value === 'string') return EVM_ADDRESS.test(value) ? value.toLowerCase() : value;
546
+ if (Array.isArray(value)) return value.map(normalizeFilterAddresses);
547
+ if (value && typeof value === 'object') {
548
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalizeFilterAddresses(item)]));
549
+ }
550
+ return value;
551
+ }
@@ -323,12 +323,14 @@ export async function resolveSolanaWallet(walletName, deps = {}) {
323
323
  }
324
324
 
325
325
  if (wallet.provider === 'privy') {
326
- const { PrivyClient } = await import('./privy.js');
326
+ const { PrivyClient, assertPrivyWalletAddress } = await import('./privy.js');
327
327
  const privyClient = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
328
+ const walletId = wallet.privyWalletIds?.solana;
329
+ await assertPrivyWalletAddress(privyClient, walletId, wallet.solana, 'solana');
328
330
  return {
329
331
  pubkey: wallet.solana,
330
332
  walletType: 'privy',
331
- walletInfo: { privyClient, walletId: wallet.privyWalletIds?.solana },
333
+ walletInfo: { privyClient, walletId },
332
334
  privyWalletIds: wallet.privyWalletIds,
333
335
  };
334
336
  }
@@ -905,10 +907,17 @@ EXAMPLES:
905
907
  const state = options.state;
906
908
  const mint = options.mint ? resolveTokenAddress(options.mint, 'solana') : undefined;
907
909
  const limit = options.limit || 20;
908
- const offset = options.offset || 0;
910
+ // parseArgs keeps numbers as strings; the footer below adds to offset.
911
+ const offset = options.offset == null ? 0 : Number(options.offset);
909
912
  const sort = options.sort;
910
913
  const dir = options.dir || 'desc';
911
914
 
915
+ if (!/^\d+$/.test(String(options.offset ?? 0)) || !Number.isSafeInteger(offset)) {
916
+ log(`Error: --offset must be a non-negative integer; received: ${options.offset}`);
917
+ exit(1);
918
+ return;
919
+ }
920
+
912
921
  if (mint) {
913
922
  const mintValidation = validateTokenAddress(mint, 'solana');
914
923
  if (!mintValidation.valid) {
package/src/perp.js CHANGED
@@ -621,9 +621,10 @@ async function resolveSigningCtx(wallet, log) {
621
621
  log,
622
622
  };
623
623
  if (wallet.provider === 'privy') {
624
- const { PrivyClient } = await import('./privy.js');
624
+ const { PrivyClient, assertPrivyWalletAddress } = await import('./privy.js');
625
625
  ctx.privyClient = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
626
626
  ctx.privyWalletId = wallet.privyWalletIds?.evm;
627
+ await assertPrivyWalletAddress(ctx.privyClient, ctx.privyWalletId, wallet.address, 'evm');
627
628
  } else {
628
629
  ctx.privateKeyHex = resolvePrivateKey(wallet);
629
630
  }