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/api.js CHANGED
@@ -14,6 +14,8 @@ import { getAnonymousId, TELEMETRY_DISABLED } from './telemetry.js';
14
14
  import { readResponseMeta, stringHeader } from './response-meta.js';
15
15
  import { trace, traceRequest, traceResponse, traceError, traceRetry, traceCacheHit } from './debug.js';
16
16
  import { appendPaymentRecord, newPaymentId, sanitizeRequestUrl } from './x402-audit.js';
17
+ import { openLocalFile } from './local-file.js';
18
+ import { ENTRY_MAX_AGE_MS, isStaleTemp, pruneResponseCacheDir } from './response-cache-files.js';
17
19
 
18
20
  /**
19
21
  * Key for the credit/rate-limit metadata attached to a successful response.
@@ -82,50 +84,13 @@ export const { version: packageVersion } = JSON.parse(
82
84
 
83
85
  // ============= Error Codes =============
84
86
 
85
- /**
86
- * Structured error codes for programmatic handling by AI agents
87
- */
88
- export const ErrorCode = {
89
- // Authentication & Authorization
90
- UNAUTHORIZED: 'UNAUTHORIZED', // 401 - Invalid or missing API key
91
- FORBIDDEN: 'FORBIDDEN', // 403 - Valid key but insufficient permissions
92
- CREDITS_EXHAUSTED: 'CREDITS_EXHAUSTED', // 403 - Insufficient API credits
93
- PLAN_UPGRADE_REQUIRED: 'PLAN_UPGRADE_REQUIRED', // 403 - Feature needs a higher subscription plan
94
- GEO_BLOCKED: 'GEO_BLOCKED', // 451 - Not available in the caller's region
95
- PAYMENT_REQUIRED: 'PAYMENT_REQUIRED', // 402 - x402 payment required
96
-
97
- // Rate Limiting
98
- RATE_LIMITED: 'RATE_LIMITED', // 429 - Too many requests
99
-
100
- // Validation Errors
101
- INVALID_ADDRESS: 'INVALID_ADDRESS', // Address format validation failed
102
- INVALID_TOKEN: 'INVALID_TOKEN', // Token address validation failed
103
- INVALID_CHAIN: 'INVALID_CHAIN', // Unsupported or invalid chain
104
- INVALID_PARAMS: 'INVALID_PARAMS', // Generic parameter validation error
105
- MISSING_PARAM: 'MISSING_PARAM', // Required parameter not provided
106
- UNSUPPORTED_FILTER: 'UNSUPPORTED_FILTER', // Filter not supported for this token/chain
107
- QUERY_TOO_LARGE: 'QUERY_TOO_LARGE', // Query would return too much data - narrow it; retrying will not help
108
- PAYLOAD_TOO_LARGE: 'PAYLOAD_TOO_LARGE', // 413 - Request body exceeds the size limit
109
-
110
- // Resource Errors
111
- NOT_FOUND: 'NOT_FOUND', // 404 - Resource not found
112
- TOKEN_NOT_FOUND: 'TOKEN_NOT_FOUND', // Token doesn't exist
113
- ADDRESS_NOT_FOUND: 'ADDRESS_NOT_FOUND', // Address has no data
114
- METHOD_NOT_ALLOWED: 'METHOD_NOT_ALLOWED', // 405 - HTTP method not allowed for this endpoint
115
- CONFLICT: 'CONFLICT', // 409 - Request conflicts with the current state
116
-
117
- // Server Errors
118
- SERVER_ERROR: 'SERVER_ERROR', // 500+ - Nansen API internal error
119
- SERVICE_UNAVAILABLE: 'SERVICE_UNAVAILABLE', // 503 - API temporarily down
120
-
121
- // Client Errors
122
- NETWORK_ERROR: 'NETWORK_ERROR', // Connection failed
123
- TIMEOUT: 'TIMEOUT', // Request timed out
124
- PAYMENT_AMBIGUOUS: 'PAYMENT_AMBIGUOUS', // x402 payment outcome unknown after transmission — do not retry with another payment
125
-
126
- // Generic
127
- UNKNOWN: 'UNKNOWN', // Unclassified error
128
- };
87
+ // The full, documented code list lives in src/error-codes.js (see
88
+ // docs/error-codes.md). Re-exported here because most modules import it from
89
+ // this file.
90
+ import { ErrorCode } from './error-codes.js';
91
+
92
+ export { ErrorCode };
93
+ export { ERROR_CODES, FIELD_ERROR_CODES } from './error-codes.js';
129
94
 
130
95
  /**
131
96
  * Error thrown by command handlers for user-facing failures (validation errors,
@@ -237,6 +202,89 @@ export function browserSessionResponseMeta(response) {
237
202
  return { ...(meta?.credits && { credits: meta.credits }), ...(meta?.rateLimit && { rateLimit: meta.rateLimit }) };
238
203
  }
239
204
 
205
+ // Validation failures (400/422) name the bad field in the body. A browser
206
+ // session drops the body of every other error so nothing token-bearing can be
207
+ // echoed, but these field-level parts only repeat request input, which the
208
+ // caller already has. Each string is bounded and dropped if it contains a
209
+ // credential, so a server that echoes headers still leaks nothing.
210
+ const SESSION_VALIDATION_STATUSES = new Set([400, 422]);
211
+ const API_KEY_PAGE = 'https://app.nansen.ai/api?tab=api';
212
+ const MAX_ECHOED_STRING = 1000;
213
+ const MAX_ECHOED_FIELD_ERRORS = 100;
214
+
215
+ export function sessionValidationDetails(data, secrets = []) {
216
+ if (data === null || typeof data !== 'object' || Array.isArray(data)) return null;
217
+ const safe = value => (typeof value === 'string' && value.length > 0 && value.length <= MAX_ECHOED_STRING
218
+ && !secrets.some(secret => secret && value.includes(secret)) ? value : undefined);
219
+ const errors = Array.isArray(data.errors)
220
+ ? data.errors.slice(0, MAX_ECHOED_FIELD_ERRORS)
221
+ .map(entry => ({ field: safe(entry?.field), message: safe(entry?.message), code: safe(entry?.code) }))
222
+ .filter(entry => entry.field && entry.message)
223
+ .map(entry => (entry.code ? entry : { field: entry.field, message: entry.message }))
224
+ : [];
225
+ const message = safe(data.message) ?? errors[0]?.message;
226
+ if (!message) return null;
227
+ const details = {};
228
+ for (const key of ['code', 'param', 'doc_url']) {
229
+ const value = safe(data[key]);
230
+ if (value) details[key] = value;
231
+ }
232
+ if (errors.length) details.errors = errors;
233
+ return { message, details };
234
+ }
235
+
236
+ /** Credential values a browser-session error must never echo. */
237
+ function credentialSecrets(headers = {}) {
238
+ const secrets = [];
239
+ for (const [name, value] of Object.entries(headers)) {
240
+ if (typeof value !== 'string' || !['authorization', 'apikey'].includes(name.toLowerCase())) continue;
241
+ secrets.push(value);
242
+ const bearer = value.match(/^Bearer\s+(.+)$/i);
243
+ if (bearer) secrets.push(bearer[1]);
244
+ }
245
+ return secrets;
246
+ }
247
+
248
+ /**
249
+ * The API error body as `details`, without the copies of what the envelope
250
+ * already carries: the message (top-level `error`), the HTTP status and the
251
+ * request id (top-level `requestId`). The per-field `errors[]` list stays.
252
+ */
253
+ export function apiErrorDetails(data, message, status) {
254
+ const details = { ...data };
255
+ const sameText = value => typeof value === 'string' && typeof message === 'string'
256
+ && value.trim() !== '' && message.includes(value.replace(/\.+$/, ''));
257
+ if (sameText(details.message)) delete details.message;
258
+ if (sameText(details.error)) delete details.error;
259
+ if (details.status === status) delete details.status;
260
+ if (typeof details.request_id === 'string') {
261
+ details.requestId ??= details.request_id;
262
+ delete details.request_id;
263
+ }
264
+ return details;
265
+ }
266
+
267
+ /** Why the connection failed, from the fetch error's cause (ENOTFOUND, ECONNREFUSED, ...). */
268
+ function networkFailureReason(err) {
269
+ const cause = err?.cause;
270
+ const code = [cause?.code, cause?.errors?.[0]?.code].find(value => typeof value === 'string' && value);
271
+ if (code) return code;
272
+ if (err?.name === 'AbortError' || err?.name === 'TimeoutError') return 'timed out';
273
+ if (typeof cause?.message === 'string' && cause.message) return cause.message;
274
+ return typeof err?.message === 'string' && err.message ? err.message : 'connection failed';
275
+ }
276
+
277
+ /**
278
+ * NETWORK_ERROR message. It says plainly that the credential was never
279
+ * checked, so a caller fixes the connection instead of replacing a valid key.
280
+ */
281
+ export function networkErrorMessage(baseUrl, err, { redact = false } = {}) {
282
+ let origin = baseUrl;
283
+ try { origin = new URL(baseUrl).origin; } catch { /* keep the raw value */ }
284
+ const reason = networkFailureReason(err);
285
+ return `Could not reach the Nansen API at ${origin}${redact ? '' : ` (${reason})`}. Check your internet connection, VPN, proxy or firewall, then retry. Your credentials were not checked, so this is not an API key problem.`;
286
+ }
287
+
240
288
  /**
241
289
  * Map an error response to an error code.
242
290
  *
@@ -376,51 +424,67 @@ function getCacheKey(endpoint, body, context = {}) {
376
424
  /**
377
425
  * Get cached response if valid
378
426
  */
379
- export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL, context = {}) {
427
+ export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL, context = {}, onHit = null) {
380
428
  const cacheKey = getCacheKey(endpoint, body, context);
381
429
  const cacheFile = path.join(CACHE_DIR, `${cacheKey}.json`);
430
+ // The sweep after a write keeps entries this process may still read.
431
+ if (Number.isFinite(ttlSeconds) && ttlSeconds > largestReadTtlSeconds) largestReadTtlSeconds = ttlSeconds;
382
432
 
383
433
  if (!fs.existsSync(cacheFile)) {
384
434
  return null;
385
435
  }
386
436
 
437
+ let fd;
438
+ let primaryError;
439
+ let result = null;
387
440
  try {
388
- const cached = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
441
+ fd = openLocalFile(cacheFile, { root: CACHE_DIR });
442
+ const cached = JSON.parse(fs.readFileSync(fd, 'utf8'));
389
443
  const age = (Date.now() - cached.timestamp) / 1000;
390
444
 
391
- if (!Number.isFinite(cached.timestamp) || ttlSeconds <= 0 || age > ttlSeconds) {
392
- // Delete entries with invalid timestamps, expired entries, or disabled entries.
393
- fs.unlinkSync(cacheFile);
394
- return null;
445
+ if (Number.isFinite(cached.timestamp) && ttlSeconds > 0 && age <= ttlSeconds) {
446
+ // Re-attach the cache marker without reshaping the payload. Object-spreading
447
+ // a top-level array turns it into { 0: …, 1: … }, so a cached array came back
448
+ // as an object and every Array.isArray() branch downstream (the table/CSV/
449
+ // markdown formatters in cli.js, alertsGet) stopped recognising it — the first
450
+ // call rendered rows and the second rendered nothing. Arrays therefore get
451
+ // _meta hung off the array itself, exactly as the live request path does when
452
+ // it records retriedAttempts, and primitives are handed back untouched
453
+ // because a non-object cannot carry the marker at all.
454
+ const meta = { ...cached.data?._meta, fromCache: true, cacheAge: Math.round(age) };
455
+ if (Array.isArray(cached.data)) {
456
+ const rows = cached.data.slice();
457
+ rows._meta = meta;
458
+ result = rows;
459
+ } else if (cached.data === null || typeof cached.data !== 'object') {
460
+ result = cached.data;
461
+ } else {
462
+ result = { ...cached.data, _meta: meta };
463
+ }
464
+ const warningMeta = typeof cached.warning === 'string' && cached.warning
465
+ ? { notices: { warning: cached.warning } } : null;
466
+ if (result !== null && typeof result === 'object' && warningMeta) result[RESPONSE_META] = warningMeta;
467
+ onHit?.(warningMeta);
395
468
  }
396
-
397
- // Re-attach the cache marker without reshaping the payload. Object-spreading
398
- // a top-level array turns it into { 0: …, 1: … }, so a cached array came back
399
- // as an object and every Array.isArray() branch downstream (the table/CSV/
400
- // markdown formatters in cli.js, alertsGet) stopped recognising it — the first
401
- // call rendered rows and the second rendered nothing. Arrays therefore get
402
- // _meta hung off the array itself, exactly as the live request path does when
403
- // it records retriedAttempts, and primitives are handed back untouched
404
- // because a non-object cannot carry the marker at all.
405
- const meta = { ...cached.data?._meta, fromCache: true, cacheAge: Math.round(age) };
406
- if (Array.isArray(cached.data)) {
407
- const rows = cached.data.slice();
408
- rows._meta = meta;
409
- return rows;
469
+ } catch (error) {
470
+ primaryError = error;
471
+ }
472
+ let closeError;
473
+ if (fd !== undefined) {
474
+ try {
475
+ fs.closeSync(fd);
476
+ } catch (error) {
477
+ closeError = error;
410
478
  }
411
- if (cached.data === null || typeof cached.data !== 'object') return cached.data;
412
- return { ...cached.data, _meta: meta };
413
- } catch (_e) {
414
- // Invalid cache file, delete it
415
- try { fs.unlinkSync(cacheFile); } catch { /* ignore */ }
416
- return null;
417
479
  }
480
+ if (!primaryError && closeError) throw closeError;
481
+ return result;
418
482
  }
419
483
 
420
484
  /**
421
485
  * Save response to cache
422
486
  */
423
- export function setCachedResponse(endpoint, body, data, context = {}) {
487
+ export function setCachedResponse(endpoint, body, data, context = {}, responseMeta = data?.[RESPONSE_META]) {
424
488
  if (!fs.existsSync(CACHE_DIR)) {
425
489
  fs.mkdirSync(CACHE_DIR, { mode: 0o700, recursive: true });
426
490
  }
@@ -431,26 +495,93 @@ export function setCachedResponse(endpoint, body, data, context = {}) {
431
495
  const cached = {
432
496
  timestamp: Date.now(),
433
497
  endpoint,
498
+ warning: responseMeta?.notices?.warning,
434
499
  data
435
500
  };
436
501
 
437
- fs.writeFileSync(cacheFile, JSON.stringify(cached), { mode: 0o600 });
502
+ const contents = JSON.stringify(cached);
503
+ const tempFile = `${cacheFile}.${process.pid}.${crypto.randomUUID()}.tmp`;
504
+ let fd;
505
+ let primaryError;
506
+ try {
507
+ fd = openLocalFile(tempFile, {
508
+ root: CACHE_DIR,
509
+ flags: fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL,
510
+ mode: 0o600,
511
+ });
512
+ if (process.platform !== 'win32') fs.fchmodSync(fd, 0o600);
513
+ fs.writeFileSync(fd, contents);
514
+ fs.fsyncSync(fd);
515
+ if (process.platform !== 'win32') fs.fchmodSync(fd, 0o600);
516
+ fs.closeSync(fd);
517
+ fd = undefined;
518
+ fs.renameSync(tempFile, cacheFile);
519
+ } catch (error) {
520
+ primaryError = error;
521
+ }
522
+ let closeError;
523
+ if (fd !== undefined) {
524
+ try {
525
+ fs.closeSync(fd);
526
+ } catch (error) {
527
+ closeError = error;
528
+ }
529
+ }
530
+ try { fs.unlinkSync(tempFile); } catch { /* rename may already have committed */ }
531
+ if (primaryError) throw primaryError;
532
+ if (closeError) throw closeError;
533
+ sweepResponseCache(cacheFile);
534
+ }
535
+
536
+ // Sweep old entries and abandoned temp files after the first successful write
537
+ // in a process, then at most once per RESPONSE_CACHE_SWEEP_INTERVAL_MS so a
538
+ // long-running process keeps sweeping. Best effort: the response is already
539
+ // cached and a failed sweep must not fail the request. Ages are measured
540
+ // against the mtime of the entry just written rather than Date.now(), so every
541
+ // file is judged by the same clock (a network filesystem may stamp its own
542
+ // time) and the new entry itself is never older than the window. Entries this
543
+ // process may still read with a longer TTL are kept.
544
+ const RESPONSE_CACHE_SWEEP_INTERVAL_MS = 60 * 60 * 1000;
545
+ let lastResponseCacheSweep;
546
+ let largestReadTtlSeconds = 0;
547
+ function sweepResponseCache(writtenFile) {
548
+ const now = Date.now();
549
+ if (lastResponseCacheSweep !== undefined && now - lastResponseCacheSweep < RESPONSE_CACHE_SWEEP_INTERVAL_MS) return;
550
+ lastResponseCacheSweep = now;
551
+ try {
552
+ const retentionMs = Math.max(ENTRY_MAX_AGE_MS, largestReadTtlSeconds * 1000);
553
+ pruneResponseCacheDir(CACHE_DIR, fs.lstatSync(writtenFile).mtimeMs, retentionMs);
554
+ } catch {
555
+ // The next process tries again.
556
+ }
438
557
  }
439
558
 
440
559
  /**
441
560
  * Clear all cached responses
442
561
  */
443
562
  export function clearCache() {
444
- if (fs.existsSync(CACHE_DIR)) {
445
- const files = fs.readdirSync(CACHE_DIR);
446
- for (const file of files) {
447
- if (file.endsWith('.json')) {
448
- fs.unlinkSync(path.join(CACHE_DIR, file));
563
+ // Like the sweep and `nansen cache clear`, never follow a symlinked cache
564
+ // directory: deletes stay inside the directory itself.
565
+ const dirStat = fs.lstatSync(CACHE_DIR, { throwIfNoEntry: false });
566
+ if (!dirStat?.isDirectory()) return 0;
567
+ const files = fs.readdirSync(CACHE_DIR);
568
+ const now = Date.now();
569
+ let removed = 0;
570
+ for (const file of files) {
571
+ const full = path.join(CACHE_DIR, file);
572
+ if (file.endsWith('.json')) {
573
+ fs.unlinkSync(full);
574
+ removed += 1;
575
+ } else {
576
+ // A temp file younger than this may belong to a write in progress.
577
+ const stat = fs.lstatSync(full, { throwIfNoEntry: false });
578
+ if (stat?.isFile() && isStaleTemp(file, stat, now)) {
579
+ fs.unlinkSync(full);
580
+ removed += 1;
449
581
  }
450
582
  }
451
- return files.length;
452
583
  }
453
- return 0;
584
+ return removed;
454
585
  }
455
586
 
456
587
  /**
@@ -544,6 +675,9 @@ function resolveCounterpartiesBatchChain(chain) {
544
675
  return resolved;
545
676
  }
546
677
 
678
+ /** The address the API uses for native BTC on token endpoints that accept bitcoin. */
679
+ export const BITCOIN_NATIVE_ADDRESS = '1111111111111111111114oLvT2';
680
+
547
681
  /**
548
682
  * Validate address format for a given chain
549
683
  * @param {string} address - The address to validate
@@ -567,7 +701,7 @@ export function validateAddress(address, chain = 'ethereum') {
567
701
  }
568
702
  } else if (chain === 'bitcoin') {
569
703
  if (!ADDRESS_PATTERNS.bitcoin.test(trimmed)) {
570
- return { valid: false, error: `Invalid Bitcoin address format.`, code: ErrorCode.INVALID_ADDRESS };
704
+ return { valid: false, error: `Invalid Bitcoin address format. Expected a legacy (1...), P2SH (3...) or bech32 (bc1...) address. For native BTC use ${BITCOIN_NATIVE_ADDRESS}.`, code: ErrorCode.INVALID_ADDRESS };
571
705
  }
572
706
  }
573
707
  // For unknown chains, allow any non-empty string (API will validate)
@@ -770,7 +904,11 @@ export class NansenAPI {
770
904
  this.paginatedResponseMeta = null;
771
905
  /** API path paired with paginatedResponseMeta for fallback cost estimates. */
772
906
  this.paginatedEndpoint = null;
773
- /** API path of the most recent request(), for pairing lastResponseMeta with a cost estimate. */
907
+ /**
908
+ * API path of the most recent live request(), for pairing lastResponseMeta
909
+ * with a cost estimate. A cache hit leaves both alone, so a cached call
910
+ * after a live one never borrows the live call's metadata for its own path.
911
+ */
774
912
  this.lastEndpoint = null;
775
913
  /**
776
914
  * Whether the most recent request() was answered from the local response
@@ -979,12 +1117,12 @@ export class NansenAPI {
979
1117
  }
980
1118
  const meta = readResponseMeta(paidResponse);
981
1119
  this.lastResponseMeta = meta;
1120
+ options.onResponseMeta?.(meta, false);
982
1121
  if (meta && data !== null && typeof data === 'object') data[RESPONSE_META] = meta;
983
1122
  return data;
984
1123
  }
985
1124
 
986
1125
  async request(endpoint, body = {}, options = {}) {
987
- this.lastEndpoint = endpoint;
988
1126
  const extraHeaders = { ...this.defaultHeaders, ...options.headers };
989
1127
  let credentialHeaders = await this.requestCredentials(extraHeaders);
990
1128
  // Keys and browser sessions share the same payment policy. Explicit raw
@@ -1014,14 +1152,25 @@ export class NansenAPI {
1014
1152
 
1015
1153
  let cacheContext = credentialContext();
1016
1154
  if (useCache && cacheContext) {
1017
- const cached = getCachedResponse(endpoint, body, cacheTtl, cacheContext);
1018
- if (cached) {
1155
+ let hit = false;
1156
+ const cached = getCachedResponse(endpoint, body, cacheTtl, cacheContext, meta => {
1157
+ hit = true;
1158
+ options.onResponseMeta?.(meta, true);
1159
+ const warning = meta?.notices?.warning;
1160
+ if (warning) {
1161
+ const previous = this.lastResponseMeta;
1162
+ const combined = [...new Set([previous?.notices?.warning, warning].filter(Boolean))].join(', ');
1163
+ this.lastResponseMeta = { ...previous, notices: { ...previous?.notices, warning: combined } };
1164
+ }
1165
+ });
1166
+ if (hit) {
1019
1167
  this.servedFromCache = true;
1020
1168
  traceCacheHit({ method, url });
1021
1169
  return cached;
1022
1170
  }
1023
1171
  }
1024
1172
  this.servedFromCache = false;
1173
+ this.lastEndpoint = endpoint;
1025
1174
 
1026
1175
  let lastError;
1027
1176
 
@@ -1059,7 +1208,7 @@ export class NansenAPI {
1059
1208
  // Network-level errors - retry these too
1060
1209
  traceError({ method, url, durationMs: Date.now() - startedAt, attempt: attempt + 1, error: this.redactAuthDiagnostics ? 'API request failed' : err.message });
1061
1210
  lastError = new NansenError(
1062
- this.selection.kind === 'session' ? 'API request failed. Check your connection and retry.' : `Network error: ${err.message}`,
1211
+ networkErrorMessage(this.baseUrl, err, { redact: this.selection.kind === 'session' }),
1063
1212
  ErrorCode.NETWORK_ERROR,
1064
1213
  null,
1065
1214
  { ...(this.selection.kind !== 'session' && { originalError: err.message }), attempt: attempt + 1 }
@@ -1117,10 +1266,13 @@ export class NansenAPI {
1117
1266
  lastError = error;
1118
1267
  continue;
1119
1268
  }
1269
+ options.onResponseMeta?.(meta, false);
1120
1270
  throw error;
1121
1271
  }
1122
1272
 
1123
1273
  if (!response.ok) {
1274
+ // A literal `null` body parses as JSON but has no fields to read.
1275
+ if (data == null) data = {};
1124
1276
  let message = data.message || data.error
1125
1277
  || (typeof data.detail === 'string' ? data.detail : data.detail?.message)
1126
1278
  || `API error: ${response.status}`;
@@ -1131,19 +1283,35 @@ export class NansenAPI {
1131
1283
  const nestedMatch = typeof message === 'string' && message.match(/['"]message['"]\s*:\s*['"](.*?)['"]\s*[,}]/s);
1132
1284
  if (nestedMatch) message = nestedMatch[1];
1133
1285
  const safeSessionError = this.selection.kind === 'session' ? browserSessionError(response.status, data) : null;
1134
- const code = safeSessionError?.code || statusToErrorCode(response.status, data);
1286
+ let code = safeSessionError?.code || statusToErrorCode(response.status, data);
1135
1287
  // Keep a body-only challenge available to the signer without exposing
1136
1288
  // the authenticated error body through browser-session diagnostics.
1137
1289
  const bodyPaymentRequirements = response.status === 402 ? data.paymentRequirements : undefined;
1138
1290
  const retryAfterMs = parseRetryAfter(response.headers.get('retry-after'));
1139
1291
  if (this.selection.kind === 'session') {
1140
- message = safeSessionError.message;
1141
- data = {}; // Authenticated errors must not echo access tokens into output.
1292
+ // Authenticated errors must not echo access tokens into output. A
1293
+ // validation failure keeps only its field-level parts, so the caller
1294
+ // still learns which field to fix.
1295
+ const validation = SESSION_VALIDATION_STATUSES.has(response.status)
1296
+ ? sessionValidationDetails(data, credentialSecrets(credentialHeaders))
1297
+ : null;
1298
+ message = validation?.message ?? safeSessionError.message;
1299
+ data = validation?.details ?? {};
1300
+ // Same code as with an API key (missing_field -> MISSING_PARAM, ...).
1301
+ if (validation) code = statusToErrorCode(response.status, validation.details);
1142
1302
  }
1143
1303
 
1144
1304
  // Enhance messages for specific error codes
1145
1305
  if (code === ErrorCode.UNAUTHORIZED) {
1146
- message = this.apiKey || safeSessionError ? message : 'Not logged in. Run: nansen login';
1306
+ if (this.apiKey && !safeSessionError) {
1307
+ // The server's sentence already says the key was rejected and
1308
+ // usually links the key page; add only what it leaves out.
1309
+ const serverMessage = String(message).replace(/\.+$/, '');
1310
+ const keyPage = serverMessage.includes(API_KEY_PAGE) ? '' : ` at ${API_KEY_PAGE}`;
1311
+ message = `${serverMessage}. The connection works; run nansen login or rotate the key${keyPage}.`;
1312
+ } else if (!safeSessionError) {
1313
+ message = 'Not logged in. Run: nansen login';
1314
+ }
1147
1315
  } else if (code === ErrorCode.UNSUPPORTED_FILTER) {
1148
1316
  message = message.replace(/\.+$/, '') + '. This filter is not supported for this token/chain combination. Do not retry.';
1149
1317
  } else if (code === ErrorCode.CREDITS_EXHAUSTED) {
@@ -1301,7 +1469,7 @@ export class NansenAPI {
1301
1469
  const meta = this.selection.kind === 'session' ? browserSessionResponseMeta(response) : readResponseMeta(response);
1302
1470
  this.lastResponseMeta = meta;
1303
1471
  lastError = new NansenError(message, code, response.status, {
1304
- ...data,
1472
+ ...apiErrorDetails(data, message, response.status),
1305
1473
  attempt: attempt + 1,
1306
1474
  retryAfterMs,
1307
1475
  ...(meta?.requestId && { requestId: meta.requestId }),
@@ -1334,6 +1502,7 @@ export class NansenAPI {
1334
1502
  continue;
1335
1503
  }
1336
1504
 
1505
+ options.onResponseMeta?.(meta, false);
1337
1506
  throw lastError;
1338
1507
  }
1339
1508
 
@@ -1342,18 +1511,14 @@ export class NansenAPI {
1342
1511
  data._meta = { ...(data._meta || {}), retriedAttempts: attempt };
1343
1512
  }
1344
1513
 
1345
- // Cache successful response
1346
- if (useCache && cacheContext) {
1347
- setCachedResponse(endpoint, body, data, cacheContext);
1348
- }
1349
-
1350
- // Attach after caching so the cache stores the payload alone — quota
1351
- // numbers are per-response and would be stale on a cache hit.
1352
- // Guarded: a response body can be a primitive, which cannot take a property.
1514
+ // Symbols do not serialize into the payload. The cache persists only the
1515
+ // durable warning separately; quota and request metadata remain live-only.
1353
1516
  const meta = readResponseMeta(response);
1354
1517
  this.lastResponseMeta = meta;
1355
- if (meta) {
1356
- if (data !== null && typeof data === 'object') data[RESPONSE_META] = meta;
1518
+ options.onResponseMeta?.(meta, false);
1519
+ if (meta && data !== null && typeof data === 'object') data[RESPONSE_META] = meta;
1520
+ if (useCache && cacheContext) {
1521
+ setCachedResponse(endpoint, body, data, cacheContext, meta);
1357
1522
  }
1358
1523
 
1359
1524
  return data;
@@ -1455,7 +1620,7 @@ export class NansenAPI {
1455
1620
  // ============= Profiler Endpoints =============
1456
1621
 
1457
1622
  async addressBalance(params = {}) {
1458
- const { address, entityName, chain = 'all', hideSpamToken = true, filters = {}, orderBy } = params;
1623
+ const { address, entityName, chain = 'all', hideSpamToken = true, filters = {}, orderBy, pagination } = params;
1459
1624
  if (address) requireValidAddress(address, chain);
1460
1625
  return this.request('/api/v1/profiler/address/current-balance', {
1461
1626
  address,
@@ -1463,7 +1628,8 @@ export class NansenAPI {
1463
1628
  chain,
1464
1629
  hide_spam_token: hideSpamToken,
1465
1630
  filters,
1466
- order_by: orderBy
1631
+ order_by: orderBy,
1632
+ pagination
1467
1633
  });
1468
1634
  }
1469
1635
 
@@ -1582,7 +1748,7 @@ export class NansenAPI {
1582
1748
  const { address, chain = 'ethereum', orderBy, pagination } = params;
1583
1749
  if (address) requireValidAddress(address, chain);
1584
1750
  return this.request('/api/v1/profiler/address/related-wallets', {
1585
- address,
1751
+ wallet_address: address,
1586
1752
  chain,
1587
1753
  order_by: orderBy,
1588
1754
  pagination
@@ -1693,15 +1859,14 @@ export class NansenAPI {
1693
1859
  }
1694
1860
 
1695
1861
  async addressPnlSummary(params = {}) {
1696
- // Note: pnl-summary endpoint is non-paginated (returns aggregate stats, not a list).
1697
- // Pagination param intentionally omitted from this request.
1698
- const { address, chain = 'ethereum', orderBy, days = 30 } = params;
1862
+ // Note: pnl-summary endpoint is non-paginated (returns aggregate stats, not a list)
1863
+ // and has no order_by, so neither is sent.
1864
+ const { address, chain = 'ethereum', days = 30 } = params;
1699
1865
  if (address) requireValidAddress(address, chain);
1700
1866
  return this.request('/api/v1/profiler/address/pnl-summary', {
1701
- address,
1867
+ wallet_address: address,
1702
1868
  chain,
1703
- date: buildDateRange(days),
1704
- order_by: orderBy
1869
+ date: buildDateRange(days)
1705
1870
  });
1706
1871
  }
1707
1872
 
@@ -1809,7 +1974,7 @@ export class NansenAPI {
1809
1974
  // Apply smart money filter via filters object
1810
1975
  if (onlySmartMoney) {
1811
1976
  filters.include_smart_money_labels = filters.include_smart_money_labels ||
1812
- ['Fund', 'Smart Trader', '30D Smart Trader', '90D Smart Trader', '180D Smart Trader'];
1977
+ ['Smart Trader', '30D Smart Trader', '90D Smart Trader', '180D Smart Trader'];
1813
1978
  }
1814
1979
 
1815
1980
  return this.request('/api/v1/tgm/dex-trades', {
@@ -2046,21 +2211,18 @@ export class NansenAPI {
2046
2211
  }
2047
2212
 
2048
2213
  async pmMarketScreener(params = {}) {
2049
- const { orderBy, sortBy = 'volume_24hr', query = '', status = '', tags, minLiquidity, maxLiquidity, minUniqueTraders24h, maxUniqueTraders24h, minVolume24hr, maxVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, minPrice, maxPrice, pagination } = params;
2214
+ const { orderBy, sortBy = 'volume_24hr', query = '', status = '', tags, minLiquidity, maxLiquidity, maxUniqueTraders24h, minVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, minPrice, maxPrice, pagination } = params;
2050
2215
  const body = {
2051
- sort_by: sortBy,
2216
+ order_by: orderBy || [{ field: sortBy, direction: 'DESC' }],
2052
2217
  query,
2053
2218
  status,
2054
2219
  pagination
2055
2220
  };
2056
- if (orderBy) body.order_by = orderBy;
2057
2221
  if (tags && tags.length) body.tags = tags;
2058
2222
  if (minLiquidity != null) body.min_liquidity = minLiquidity;
2059
2223
  if (maxLiquidity != null) body.max_liquidity = maxLiquidity;
2060
- if (minUniqueTraders24h != null) body.min_unique_traders_24h = minUniqueTraders24h;
2061
2224
  if (maxUniqueTraders24h != null) body.max_unique_traders_24h = maxUniqueTraders24h;
2062
2225
  if (minVolume24hr != null) body.min_volume_24hr = minVolume24hr;
2063
- if (maxVolume24hr != null) body.max_volume_24hr = maxVolume24hr;
2064
2226
  if (negRisk != null) body.neg_risk = negRisk;
2065
2227
  if (minOpenInterest != null) body.min_open_interest = minOpenInterest;
2066
2228
  if (maxOpenInterest != null) body.max_open_interest = maxOpenInterest;
@@ -2072,21 +2234,18 @@ export class NansenAPI {
2072
2234
  }
2073
2235
 
2074
2236
  async pmEventScreener(params = {}) {
2075
- const { orderBy, sortBy = 'volume_24hr', query = '', status = '', tags, minLiquidity, maxLiquidity, minUniqueTraders24h, maxUniqueTraders24h, minVolume24hr, maxVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, pagination } = params;
2237
+ const { orderBy, sortBy = 'volume_24hr', query = '', status = '', tags, minLiquidity, maxLiquidity, maxUniqueTraders24h, minVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, pagination } = params;
2076
2238
  const body = {
2077
- sort_by: sortBy,
2239
+ order_by: orderBy || [{ field: sortBy, direction: 'DESC' }],
2078
2240
  query,
2079
2241
  status,
2080
2242
  pagination
2081
2243
  };
2082
- if (orderBy) body.order_by = orderBy;
2083
2244
  if (tags && tags.length) body.tags = tags;
2084
2245
  if (minLiquidity != null) body.min_liquidity = minLiquidity;
2085
2246
  if (maxLiquidity != null) body.max_liquidity = maxLiquidity;
2086
- if (minUniqueTraders24h != null) body.min_unique_traders_24h = minUniqueTraders24h;
2087
2247
  if (maxUniqueTraders24h != null) body.max_unique_traders_24h = maxUniqueTraders24h;
2088
2248
  if (minVolume24hr != null) body.min_volume_24hr = minVolume24hr;
2089
- if (maxVolume24hr != null) body.max_volume_24hr = maxVolume24hr;
2090
2249
  if (negRisk != null) body.neg_risk = negRisk;
2091
2250
  if (minOpenInterest != null) body.min_open_interest = minOpenInterest;
2092
2251
  if (maxOpenInterest != null) body.max_open_interest = maxOpenInterest;
@@ -2185,15 +2344,14 @@ export class NansenAPI {
2185
2344
  }
2186
2345
 
2187
2346
  async researchTokenFlowSummary(params = {}) {
2188
- // API does not support pagination on this endpoint.
2189
- const { tokenAddress, chain = 'solana', fromDate, toDate, filters = {}, orderBy } = params;
2347
+ // The endpoint returns one aggregated row: it takes no pagination,
2348
+ // filters or order_by.
2349
+ const { tokenAddress, chain = 'solana', fromDate, toDate } = params;
2190
2350
  if (tokenAddress) requireValidToken(tokenAddress, chain);
2191
2351
  return this.request('/api/v1/tgm/historical-token-flow-summary', {
2192
2352
  token_address: tokenAddress,
2193
2353
  chain,
2194
2354
  date_range: { from: fromDate, to: toDate },
2195
- filters,
2196
- order_by: orderBy,
2197
2355
  });
2198
2356
  }
2199
2357
 
@@ -5,6 +5,7 @@ import { fileURLToPath } from 'node:url';
5
5
  import { readLocalFile } from './local-file.js';
6
6
 
7
7
  export const DEFAULT_API_ORIGIN = 'https://api.nansen.ai';
8
+ export const ENV_API_KEY_GUIDANCE = "You can still use the CLI with an API key. Get your API key from https://app.nansen.ai/api. On macOS/Linux, run: export NANSEN_API_KEY='<your-api-key>'. On Windows PowerShell, run: $env:NANSEN_API_KEY = '<your-api-key>'. Then check access with: nansen account. This works without a credential store or native authentication locking. You don't need to run nansen login. The variable stays set for this terminal session. For CI or automation, supply NANSEN_API_KEY through your platform's secret manager.";
8
9
  const DEV_CONFIG = fileURLToPath(new URL('../config.json', import.meta.url));
9
10
  export class AuthError extends Error {
10
11
  constructor(code, message) { super(message); this.code = code; }