nansen-cli 2.3.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +32 -32
  3. package/docs/auth.md +56 -0
  4. package/docs/browser-login.md +101 -7
  5. package/docs/error-codes.md +249 -0
  6. package/package.json +10 -4
  7. package/skills/nansen-agent-guide/SKILL.md +17 -1
  8. package/skills/nansen-alerts-webhook-listener/SKILL.md +1 -1
  9. package/skills/nansen-dca-tracker/SKILL.md +1 -1
  10. package/skills/nansen-defi-positions/SKILL.md +1 -1
  11. package/skills/nansen-exit-signals/SKILL.md +2 -2
  12. package/skills/nansen-fund-tracker/SKILL.md +1 -1
  13. package/skills/nansen-general-search/SKILL.md +1 -1
  14. package/skills/nansen-holder-analysis/SKILL.md +2 -2
  15. package/skills/nansen-limit-orders/SKILL.md +1 -1
  16. package/skills/nansen-mpp-payment/SKILL.md +2 -2
  17. package/skills/nansen-perp-screener/SKILL.md +1 -1
  18. package/skills/nansen-perp-trader-profile/SKILL.md +1 -1
  19. package/skills/nansen-polymarket-deep-dive/SKILL.md +1 -1
  20. package/skills/nansen-polymarket-insider-scan/SKILL.md +1 -1
  21. package/skills/nansen-polymarket-trader-profile/SKILL.md +1 -1
  22. package/skills/nansen-portfolio-tracker/SKILL.md +1 -1
  23. package/skills/nansen-prediction-markets/SKILL.md +1 -1
  24. package/skills/nansen-sm-cross-chain-flows/SKILL.md +1 -1
  25. package/skills/nansen-smart-alerts/SKILL.md +2 -1
  26. package/skills/nansen-smart-money-alpha/SKILL.md +1 -1
  27. package/skills/nansen-smart-money-tracker/SKILL.md +8 -7
  28. package/skills/nansen-smart-money-trend/SKILL.md +1 -1
  29. package/skills/nansen-token-research/SKILL.md +1 -1
  30. package/skills/nansen-token-screener/SKILL.md +1 -1
  31. package/skills/nansen-token-transfer-analysis/SKILL.md +1 -1
  32. package/skills/nansen-trading/SKILL.md +1 -1
  33. package/skills/nansen-wallet-batch/SKILL.md +1 -1
  34. package/skills/nansen-wallet-clustering/SKILL.md +1 -1
  35. package/skills/nansen-wallet-deep-dive/SKILL.md +1 -1
  36. package/skills/nansen-wallet-keychain-migration/SKILL.md +1 -1
  37. package/skills/nansen-wallet-manager/SKILL.md +1 -1
  38. package/skills/nansen-wallet-profiler/SKILL.md +1 -1
  39. package/skills/nansen-web-fetcher/SKILL.md +1 -1
  40. package/skills/nansen-web-searcher/SKILL.md +1 -1
  41. package/src/api-endpoints.json +1605 -0
  42. package/src/api.js +202 -97
  43. package/src/auth-credentials.js +1 -0
  44. package/src/auth-state.js +2 -2
  45. package/src/auth-store-native.js +6 -1
  46. package/src/auth-store-worker.js +1 -1
  47. package/src/auth-store.js +9 -4
  48. package/src/bridge.js +19 -10
  49. package/src/cli.js +188 -89
  50. package/src/commands/agent.js +2 -3
  51. package/src/commands/alerts.js +277 -9
  52. package/src/commands/feedback.js +98 -37
  53. package/src/commands/mcp.js +1 -1
  54. package/src/commands/research.js +14 -37
  55. package/src/cost-cache.js +33 -7
  56. package/src/doctor.js +14 -5
  57. package/src/error-codes.js +226 -0
  58. package/src/input-validation.js +551 -0
  59. package/src/limit-order.js +12 -3
  60. package/src/perp.js +2 -1
  61. package/src/privy.js +89 -11
  62. package/src/query-options.js +30 -7
  63. package/src/rpc-urls.js +3 -1
  64. package/src/schema.json +1137 -145
  65. package/src/solana-tx.js +4 -0
  66. package/src/trade-validation.js +167 -8
  67. package/src/trading.js +172 -12
  68. package/src/transfer.js +7 -1
  69. package/src/update-check.js +32 -5
  70. package/src/wallet.js +211 -57
  71. package/src/walletconnect-x402.js +14 -8
package/src/api.js CHANGED
@@ -14,6 +14,7 @@ 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';
17
18
 
18
19
  /**
19
20
  * Key for the credit/rate-limit metadata attached to a successful response.
@@ -82,50 +83,13 @@ export const { version: packageVersion } = JSON.parse(
82
83
 
83
84
  // ============= Error Codes =============
84
85
 
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
- };
86
+ // The full, documented code list lives in src/error-codes.js (see
87
+ // docs/error-codes.md). Re-exported here because most modules import it from
88
+ // this file.
89
+ import { ErrorCode } from './error-codes.js';
90
+
91
+ export { ErrorCode };
92
+ export { ERROR_CODES, FIELD_ERROR_CODES } from './error-codes.js';
129
93
 
130
94
  /**
131
95
  * Error thrown by command handlers for user-facing failures (validation errors,
@@ -237,6 +201,89 @@ export function browserSessionResponseMeta(response) {
237
201
  return { ...(meta?.credits && { credits: meta.credits }), ...(meta?.rateLimit && { rateLimit: meta.rateLimit }) };
238
202
  }
239
203
 
204
+ // Validation failures (400/422) name the bad field in the body. A browser
205
+ // session drops the body of every other error so nothing token-bearing can be
206
+ // echoed, but these field-level parts only repeat request input, which the
207
+ // caller already has. Each string is bounded and dropped if it contains a
208
+ // credential, so a server that echoes headers still leaks nothing.
209
+ const SESSION_VALIDATION_STATUSES = new Set([400, 422]);
210
+ const API_KEY_PAGE = 'https://app.nansen.ai/api?tab=api';
211
+ const MAX_ECHOED_STRING = 1000;
212
+ const MAX_ECHOED_FIELD_ERRORS = 100;
213
+
214
+ export function sessionValidationDetails(data, secrets = []) {
215
+ if (data === null || typeof data !== 'object' || Array.isArray(data)) return null;
216
+ const safe = value => (typeof value === 'string' && value.length > 0 && value.length <= MAX_ECHOED_STRING
217
+ && !secrets.some(secret => secret && value.includes(secret)) ? value : undefined);
218
+ const errors = Array.isArray(data.errors)
219
+ ? data.errors.slice(0, MAX_ECHOED_FIELD_ERRORS)
220
+ .map(entry => ({ field: safe(entry?.field), message: safe(entry?.message), code: safe(entry?.code) }))
221
+ .filter(entry => entry.field && entry.message)
222
+ .map(entry => (entry.code ? entry : { field: entry.field, message: entry.message }))
223
+ : [];
224
+ const message = safe(data.message) ?? errors[0]?.message;
225
+ if (!message) return null;
226
+ const details = {};
227
+ for (const key of ['code', 'param', 'doc_url']) {
228
+ const value = safe(data[key]);
229
+ if (value) details[key] = value;
230
+ }
231
+ if (errors.length) details.errors = errors;
232
+ return { message, details };
233
+ }
234
+
235
+ /** Credential values a browser-session error must never echo. */
236
+ function credentialSecrets(headers = {}) {
237
+ const secrets = [];
238
+ for (const [name, value] of Object.entries(headers)) {
239
+ if (typeof value !== 'string' || !['authorization', 'apikey'].includes(name.toLowerCase())) continue;
240
+ secrets.push(value);
241
+ const bearer = value.match(/^Bearer\s+(.+)$/i);
242
+ if (bearer) secrets.push(bearer[1]);
243
+ }
244
+ return secrets;
245
+ }
246
+
247
+ /**
248
+ * The API error body as `details`, without the copies of what the envelope
249
+ * already carries: the message (top-level `error`), the HTTP status and the
250
+ * request id (top-level `requestId`). The per-field `errors[]` list stays.
251
+ */
252
+ export function apiErrorDetails(data, message, status) {
253
+ const details = { ...data };
254
+ const sameText = value => typeof value === 'string' && typeof message === 'string'
255
+ && value.trim() !== '' && message.includes(value.replace(/\.+$/, ''));
256
+ if (sameText(details.message)) delete details.message;
257
+ if (sameText(details.error)) delete details.error;
258
+ if (details.status === status) delete details.status;
259
+ if (typeof details.request_id === 'string') {
260
+ details.requestId ??= details.request_id;
261
+ delete details.request_id;
262
+ }
263
+ return details;
264
+ }
265
+
266
+ /** Why the connection failed, from the fetch error's cause (ENOTFOUND, ECONNREFUSED, ...). */
267
+ function networkFailureReason(err) {
268
+ const cause = err?.cause;
269
+ const code = [cause?.code, cause?.errors?.[0]?.code].find(value => typeof value === 'string' && value);
270
+ if (code) return code;
271
+ if (err?.name === 'AbortError' || err?.name === 'TimeoutError') return 'timed out';
272
+ if (typeof cause?.message === 'string' && cause.message) return cause.message;
273
+ return typeof err?.message === 'string' && err.message ? err.message : 'connection failed';
274
+ }
275
+
276
+ /**
277
+ * NETWORK_ERROR message. It says plainly that the credential was never
278
+ * checked, so a caller fixes the connection instead of replacing a valid key.
279
+ */
280
+ export function networkErrorMessage(baseUrl, err, { redact = false } = {}) {
281
+ let origin = baseUrl;
282
+ try { origin = new URL(baseUrl).origin; } catch { /* keep the raw value */ }
283
+ const reason = networkFailureReason(err);
284
+ 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.`;
285
+ }
286
+
240
287
  /**
241
288
  * Map an error response to an error code.
242
289
  *
@@ -384,37 +431,47 @@ export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL
384
431
  return null;
385
432
  }
386
433
 
434
+ let fd;
435
+ let primaryError;
436
+ let result = null;
387
437
  try {
388
- const cached = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
438
+ fd = openLocalFile(cacheFile, { root: CACHE_DIR });
439
+ const cached = JSON.parse(fs.readFileSync(fd, 'utf8'));
389
440
  const age = (Date.now() - cached.timestamp) / 1000;
390
441
 
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;
442
+ if (Number.isFinite(cached.timestamp) && ttlSeconds > 0 && age <= ttlSeconds) {
443
+ // Re-attach the cache marker without reshaping the payload. Object-spreading
444
+ // a top-level array turns it into { 0: …, 1: … }, so a cached array came back
445
+ // as an object and every Array.isArray() branch downstream (the table/CSV/
446
+ // markdown formatters in cli.js, alertsGet) stopped recognising it — the first
447
+ // call rendered rows and the second rendered nothing. Arrays therefore get
448
+ // _meta hung off the array itself, exactly as the live request path does when
449
+ // it records retriedAttempts, and primitives are handed back untouched
450
+ // because a non-object cannot carry the marker at all.
451
+ const meta = { ...cached.data?._meta, fromCache: true, cacheAge: Math.round(age) };
452
+ if (Array.isArray(cached.data)) {
453
+ const rows = cached.data.slice();
454
+ rows._meta = meta;
455
+ result = rows;
456
+ } else if (cached.data === null || typeof cached.data !== 'object') {
457
+ result = cached.data;
458
+ } else {
459
+ result = { ...cached.data, _meta: meta };
460
+ }
395
461
  }
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;
462
+ } catch (error) {
463
+ primaryError = error;
464
+ }
465
+ let closeError;
466
+ if (fd !== undefined) {
467
+ try {
468
+ fs.closeSync(fd);
469
+ } catch (error) {
470
+ closeError = error;
410
471
  }
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
472
  }
473
+ if (!primaryError && closeError) throw closeError;
474
+ return result;
418
475
  }
419
476
 
420
477
  /**
@@ -434,7 +491,37 @@ export function setCachedResponse(endpoint, body, data, context = {}) {
434
491
  data
435
492
  };
436
493
 
437
- fs.writeFileSync(cacheFile, JSON.stringify(cached), { mode: 0o600 });
494
+ const contents = JSON.stringify(cached);
495
+ const tempFile = `${cacheFile}.${process.pid}.${crypto.randomUUID()}.tmp`;
496
+ let fd;
497
+ let primaryError;
498
+ try {
499
+ fd = openLocalFile(tempFile, {
500
+ root: CACHE_DIR,
501
+ flags: fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL,
502
+ mode: 0o600,
503
+ });
504
+ if (process.platform !== 'win32') fs.fchmodSync(fd, 0o600);
505
+ fs.writeFileSync(fd, contents);
506
+ fs.fsyncSync(fd);
507
+ if (process.platform !== 'win32') fs.fchmodSync(fd, 0o600);
508
+ fs.closeSync(fd);
509
+ fd = undefined;
510
+ fs.renameSync(tempFile, cacheFile);
511
+ } catch (error) {
512
+ primaryError = error;
513
+ }
514
+ let closeError;
515
+ if (fd !== undefined) {
516
+ try {
517
+ fs.closeSync(fd);
518
+ } catch (error) {
519
+ closeError = error;
520
+ }
521
+ }
522
+ try { fs.unlinkSync(tempFile); } catch { /* rename may already have committed */ }
523
+ if (primaryError) throw primaryError;
524
+ if (closeError) throw closeError;
438
525
  }
439
526
 
440
527
  /**
@@ -544,6 +631,9 @@ function resolveCounterpartiesBatchChain(chain) {
544
631
  return resolved;
545
632
  }
546
633
 
634
+ /** The address the API uses for native BTC on token endpoints that accept bitcoin. */
635
+ export const BITCOIN_NATIVE_ADDRESS = '1111111111111111111114oLvT2';
636
+
547
637
  /**
548
638
  * Validate address format for a given chain
549
639
  * @param {string} address - The address to validate
@@ -567,7 +657,7 @@ export function validateAddress(address, chain = 'ethereum') {
567
657
  }
568
658
  } else if (chain === 'bitcoin') {
569
659
  if (!ADDRESS_PATTERNS.bitcoin.test(trimmed)) {
570
- return { valid: false, error: `Invalid Bitcoin address format.`, code: ErrorCode.INVALID_ADDRESS };
660
+ 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
661
  }
572
662
  }
573
663
  // For unknown chains, allow any non-empty string (API will validate)
@@ -770,7 +860,11 @@ export class NansenAPI {
770
860
  this.paginatedResponseMeta = null;
771
861
  /** API path paired with paginatedResponseMeta for fallback cost estimates. */
772
862
  this.paginatedEndpoint = null;
773
- /** API path of the most recent request(), for pairing lastResponseMeta with a cost estimate. */
863
+ /**
864
+ * API path of the most recent live request(), for pairing lastResponseMeta
865
+ * with a cost estimate. A cache hit leaves both alone, so a cached call
866
+ * after a live one never borrows the live call's metadata for its own path.
867
+ */
774
868
  this.lastEndpoint = null;
775
869
  /**
776
870
  * Whether the most recent request() was answered from the local response
@@ -984,7 +1078,6 @@ export class NansenAPI {
984
1078
  }
985
1079
 
986
1080
  async request(endpoint, body = {}, options = {}) {
987
- this.lastEndpoint = endpoint;
988
1081
  const extraHeaders = { ...this.defaultHeaders, ...options.headers };
989
1082
  let credentialHeaders = await this.requestCredentials(extraHeaders);
990
1083
  // Keys and browser sessions share the same payment policy. Explicit raw
@@ -1022,6 +1115,7 @@ export class NansenAPI {
1022
1115
  }
1023
1116
  }
1024
1117
  this.servedFromCache = false;
1118
+ this.lastEndpoint = endpoint;
1025
1119
 
1026
1120
  let lastError;
1027
1121
 
@@ -1059,7 +1153,7 @@ export class NansenAPI {
1059
1153
  // Network-level errors - retry these too
1060
1154
  traceError({ method, url, durationMs: Date.now() - startedAt, attempt: attempt + 1, error: this.redactAuthDiagnostics ? 'API request failed' : err.message });
1061
1155
  lastError = new NansenError(
1062
- this.selection.kind === 'session' ? 'API request failed. Check your connection and retry.' : `Network error: ${err.message}`,
1156
+ networkErrorMessage(this.baseUrl, err, { redact: this.selection.kind === 'session' }),
1063
1157
  ErrorCode.NETWORK_ERROR,
1064
1158
  null,
1065
1159
  { ...(this.selection.kind !== 'session' && { originalError: err.message }), attempt: attempt + 1 }
@@ -1131,19 +1225,35 @@ export class NansenAPI {
1131
1225
  const nestedMatch = typeof message === 'string' && message.match(/['"]message['"]\s*:\s*['"](.*?)['"]\s*[,}]/s);
1132
1226
  if (nestedMatch) message = nestedMatch[1];
1133
1227
  const safeSessionError = this.selection.kind === 'session' ? browserSessionError(response.status, data) : null;
1134
- const code = safeSessionError?.code || statusToErrorCode(response.status, data);
1228
+ let code = safeSessionError?.code || statusToErrorCode(response.status, data);
1135
1229
  // Keep a body-only challenge available to the signer without exposing
1136
1230
  // the authenticated error body through browser-session diagnostics.
1137
1231
  const bodyPaymentRequirements = response.status === 402 ? data.paymentRequirements : undefined;
1138
1232
  const retryAfterMs = parseRetryAfter(response.headers.get('retry-after'));
1139
1233
  if (this.selection.kind === 'session') {
1140
- message = safeSessionError.message;
1141
- data = {}; // Authenticated errors must not echo access tokens into output.
1234
+ // Authenticated errors must not echo access tokens into output. A
1235
+ // validation failure keeps only its field-level parts, so the caller
1236
+ // still learns which field to fix.
1237
+ const validation = SESSION_VALIDATION_STATUSES.has(response.status)
1238
+ ? sessionValidationDetails(data, credentialSecrets(credentialHeaders))
1239
+ : null;
1240
+ message = validation?.message ?? safeSessionError.message;
1241
+ data = validation?.details ?? {};
1242
+ // Same code as with an API key (missing_field -> MISSING_PARAM, ...).
1243
+ if (validation) code = statusToErrorCode(response.status, validation.details);
1142
1244
  }
1143
1245
 
1144
1246
  // Enhance messages for specific error codes
1145
1247
  if (code === ErrorCode.UNAUTHORIZED) {
1146
- message = this.apiKey || safeSessionError ? message : 'Not logged in. Run: nansen login';
1248
+ if (this.apiKey && !safeSessionError) {
1249
+ // The server's sentence already says the key was rejected and
1250
+ // usually links the key page; add only what it leaves out.
1251
+ const serverMessage = String(message).replace(/\.+$/, '');
1252
+ const keyPage = serverMessage.includes(API_KEY_PAGE) ? '' : ` at ${API_KEY_PAGE}`;
1253
+ message = `${serverMessage}. The connection works; run nansen login or rotate the key${keyPage}.`;
1254
+ } else if (!safeSessionError) {
1255
+ message = 'Not logged in. Run: nansen login';
1256
+ }
1147
1257
  } else if (code === ErrorCode.UNSUPPORTED_FILTER) {
1148
1258
  message = message.replace(/\.+$/, '') + '. This filter is not supported for this token/chain combination. Do not retry.';
1149
1259
  } else if (code === ErrorCode.CREDITS_EXHAUSTED) {
@@ -1301,7 +1411,7 @@ export class NansenAPI {
1301
1411
  const meta = this.selection.kind === 'session' ? browserSessionResponseMeta(response) : readResponseMeta(response);
1302
1412
  this.lastResponseMeta = meta;
1303
1413
  lastError = new NansenError(message, code, response.status, {
1304
- ...data,
1414
+ ...apiErrorDetails(data, message, response.status),
1305
1415
  attempt: attempt + 1,
1306
1416
  retryAfterMs,
1307
1417
  ...(meta?.requestId && { requestId: meta.requestId }),
@@ -1455,7 +1565,7 @@ export class NansenAPI {
1455
1565
  // ============= Profiler Endpoints =============
1456
1566
 
1457
1567
  async addressBalance(params = {}) {
1458
- const { address, entityName, chain = 'all', hideSpamToken = true, filters = {}, orderBy } = params;
1568
+ const { address, entityName, chain = 'all', hideSpamToken = true, filters = {}, orderBy, pagination } = params;
1459
1569
  if (address) requireValidAddress(address, chain);
1460
1570
  return this.request('/api/v1/profiler/address/current-balance', {
1461
1571
  address,
@@ -1463,7 +1573,8 @@ export class NansenAPI {
1463
1573
  chain,
1464
1574
  hide_spam_token: hideSpamToken,
1465
1575
  filters,
1466
- order_by: orderBy
1576
+ order_by: orderBy,
1577
+ pagination
1467
1578
  });
1468
1579
  }
1469
1580
 
@@ -1693,15 +1804,14 @@ export class NansenAPI {
1693
1804
  }
1694
1805
 
1695
1806
  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;
1807
+ // Note: pnl-summary endpoint is non-paginated (returns aggregate stats, not a list)
1808
+ // and has no order_by, so neither is sent.
1809
+ const { address, chain = 'ethereum', days = 30 } = params;
1699
1810
  if (address) requireValidAddress(address, chain);
1700
1811
  return this.request('/api/v1/profiler/address/pnl-summary', {
1701
1812
  address,
1702
1813
  chain,
1703
- date: buildDateRange(days),
1704
- order_by: orderBy
1814
+ date: buildDateRange(days)
1705
1815
  });
1706
1816
  }
1707
1817
 
@@ -1809,7 +1919,7 @@ export class NansenAPI {
1809
1919
  // Apply smart money filter via filters object
1810
1920
  if (onlySmartMoney) {
1811
1921
  filters.include_smart_money_labels = filters.include_smart_money_labels ||
1812
- ['Fund', 'Smart Trader', '30D Smart Trader', '90D Smart Trader', '180D Smart Trader'];
1922
+ ['Smart Trader', '30D Smart Trader', '90D Smart Trader', '180D Smart Trader'];
1813
1923
  }
1814
1924
 
1815
1925
  return this.request('/api/v1/tgm/dex-trades', {
@@ -2046,7 +2156,7 @@ export class NansenAPI {
2046
2156
  }
2047
2157
 
2048
2158
  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;
2159
+ const { orderBy, sortBy = 'volume_24hr', query = '', status = '', tags, minLiquidity, maxLiquidity, maxUniqueTraders24h, minVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, minPrice, maxPrice, pagination } = params;
2050
2160
  const body = {
2051
2161
  sort_by: sortBy,
2052
2162
  query,
@@ -2057,10 +2167,8 @@ export class NansenAPI {
2057
2167
  if (tags && tags.length) body.tags = tags;
2058
2168
  if (minLiquidity != null) body.min_liquidity = minLiquidity;
2059
2169
  if (maxLiquidity != null) body.max_liquidity = maxLiquidity;
2060
- if (minUniqueTraders24h != null) body.min_unique_traders_24h = minUniqueTraders24h;
2061
2170
  if (maxUniqueTraders24h != null) body.max_unique_traders_24h = maxUniqueTraders24h;
2062
2171
  if (minVolume24hr != null) body.min_volume_24hr = minVolume24hr;
2063
- if (maxVolume24hr != null) body.max_volume_24hr = maxVolume24hr;
2064
2172
  if (negRisk != null) body.neg_risk = negRisk;
2065
2173
  if (minOpenInterest != null) body.min_open_interest = minOpenInterest;
2066
2174
  if (maxOpenInterest != null) body.max_open_interest = maxOpenInterest;
@@ -2072,7 +2180,7 @@ export class NansenAPI {
2072
2180
  }
2073
2181
 
2074
2182
  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;
2183
+ const { orderBy, sortBy = 'volume_24hr', query = '', status = '', tags, minLiquidity, maxLiquidity, maxUniqueTraders24h, minVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, pagination } = params;
2076
2184
  const body = {
2077
2185
  sort_by: sortBy,
2078
2186
  query,
@@ -2083,10 +2191,8 @@ export class NansenAPI {
2083
2191
  if (tags && tags.length) body.tags = tags;
2084
2192
  if (minLiquidity != null) body.min_liquidity = minLiquidity;
2085
2193
  if (maxLiquidity != null) body.max_liquidity = maxLiquidity;
2086
- if (minUniqueTraders24h != null) body.min_unique_traders_24h = minUniqueTraders24h;
2087
2194
  if (maxUniqueTraders24h != null) body.max_unique_traders_24h = maxUniqueTraders24h;
2088
2195
  if (minVolume24hr != null) body.min_volume_24hr = minVolume24hr;
2089
- if (maxVolume24hr != null) body.max_volume_24hr = maxVolume24hr;
2090
2196
  if (negRisk != null) body.neg_risk = negRisk;
2091
2197
  if (minOpenInterest != null) body.min_open_interest = minOpenInterest;
2092
2198
  if (maxOpenInterest != null) body.max_open_interest = maxOpenInterest;
@@ -2185,15 +2291,14 @@ export class NansenAPI {
2185
2291
  }
2186
2292
 
2187
2293
  async researchTokenFlowSummary(params = {}) {
2188
- // API does not support pagination on this endpoint.
2189
- const { tokenAddress, chain = 'solana', fromDate, toDate, filters = {}, orderBy } = params;
2294
+ // The endpoint returns one aggregated row: it takes no pagination,
2295
+ // filters or order_by.
2296
+ const { tokenAddress, chain = 'solana', fromDate, toDate } = params;
2190
2297
  if (tokenAddress) requireValidToken(tokenAddress, chain);
2191
2298
  return this.request('/api/v1/tgm/historical-token-flow-summary', {
2192
2299
  token_address: tokenAddress,
2193
2300
  chain,
2194
2301
  date_range: { from: fromDate, to: toDate },
2195
- filters,
2196
- order_by: orderBy,
2197
2302
  });
2198
2303
  }
2199
2304
 
@@ -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; }
package/src/auth-state.js CHANGED
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import { setTimeout as delay } from 'node:timers/promises';
5
- import { AuthError, authDirectory, validAuthPointer } from './auth-credentials.js';
5
+ import { AuthError, authDirectory, validAuthPointer, ENV_API_KEY_GUIDANCE } from './auth-credentials.js';
6
6
  import { createAuthStore } from './auth-store.js';
7
7
  import { refreshSession, retireSession, validateSession } from './auth-device.js';
8
8
  import { openLocalFile, readLocalFile } from './local-file.js';
@@ -78,7 +78,7 @@ async function waitTurn(previous, signal) {
78
78
  }
79
79
  async function loadLocks() {
80
80
  try { return (await import('fs-native-extensions')).default; }
81
- catch { throw new AuthError('AUTH_LOCK_UNAVAILABLE', 'Native authentication locking is unavailable. Reinstall nansen-cli with optional dependencies; if they are installed, this platform may lack a compatible fs-native-extensions prebuild. Legacy key setup and logout require this binding. Environment API keys still work. For offline saved-key removal, stop every CLI/auth process, then follow docs/browser-login.md#offline-recovery-without-native-locking. Do not delete auth journals or wallet files.'); }
81
+ catch { throw new AuthError('AUTH_LOCK_UNAVAILABLE', `Native authentication locking is unavailable. ${ENV_API_KEY_GUIDANCE} Saved login and logout require this binding. Reinstall nansen-cli with optional dependencies; if they are installed, this platform may lack a compatible fs-native-extensions prebuild. For offline saved-key removal, stop every CLI/auth process, then follow docs/browser-login.md#offline-recovery-without-native-locking. Do not delete auth journals or wallet files.`); }
82
82
  }
83
83
  export function createAuthState({ directory = authDirectory(), store = createAuthStore({ directory }), retire = retireSession, refresh = refreshSession, now = Date.now, barrier = async () => {}, locks = loadLocks, waitMs = 15000, operationMs = 60000 } = {}) {
84
84
  let operationSignal;
@@ -16,5 +16,10 @@ try {
16
16
  else if (operation === 'delete') value = entry.deleteCredential();
17
17
  else throw new Error();
18
18
  parentPort.postMessage({ value });
19
- } catch { parentPort.postMessage({ error: 'STORE_UNAVAILABLE' }); }
19
+ } catch (error) {
20
+ // The binding exposes GenericFailure for both cases. Recognize only the
21
+ // upstream Secret Service refusal; never forward native messages or secrets.
22
+ const locked = process.platform === 'linux' && /Secret Service: unlock prompt was dismissed/.test(error?.message || '');
23
+ parentPort.postMessage({ error: locked ? 'STORE_LOCKED' : 'STORE_UNAVAILABLE' });
24
+ }
20
25
  }
@@ -45,7 +45,7 @@ function receive(line) {
45
45
  worker.on('error', stop);
46
46
  worker.on('exit', code => {
47
47
  // No response or lock release until the executor can no longer write.
48
- if (code !== 0 || !result || (result.error && result.error !== 'BINDING_MISSING')) return stop();
48
+ if (code !== 0 || !result || (result.error && !['BINDING_MISSING', 'STORE_LOCKED', 'STORE_UNAVAILABLE'].includes(result.error))) return stop();
49
49
  process.stdout.write(JSON.stringify(result) + '\n', () => {
50
50
  clearTimeout(timer);
51
51
  fs.closeSync(fd);
package/src/auth-store.js CHANGED
@@ -2,12 +2,12 @@ import { spawn } from 'node:child_process';
2
2
  import { randomBytes, createHash } from 'node:crypto';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import path from 'node:path';
5
- import { AuthError, authDirectory } from './auth-credentials.js';
5
+ import { AuthError, authDirectory, ENV_API_KEY_GUIDANCE } from './auth-credentials.js';
6
6
 
7
7
  export const CHUNK_BYTES = 2048;
8
8
  export const MAX_BUNDLE_BYTES = 16384;
9
9
  const digest = bytes => createHash('sha256').update(bytes).digest('hex');
10
- const unavailable = () => new AuthError('AUTH_STORE_UNAVAILABLE', 'Secure credential storage is unavailable or locked. Unlock your OS credential store and retry nansen login. No file fallback is used.');
10
+ const unavailable = () => new AuthError('AUTH_STORE_UNAVAILABLE', `Secure credential storage is unavailable or locked. ${ENV_API_KEY_GUIDANCE} To use browser login, enable and unlock your OS credential store, then retry nansen login from a supported terminal. On Linux, check the user D-Bus session, Secret Service provider and default collection; installing the native binding alone does not start or unlock a service. See docs/browser-login.md#linux-secret-service-setup. No file fallback is used.`);
11
11
  export function nativeStoreOperation(operation, account, bytes, { directory = authDirectory(), signal } = {}) {
12
12
  signal?.throwIfAborted();
13
13
  return new Promise((resolve, reject) => {
@@ -47,7 +47,7 @@ export function nativeStoreOperation(operation, account, bytes, { directory = au
47
47
  // The child already holds execution/cleanup exclusion. Keep the
48
48
  // pipe open as a parent-lifetime signal; never send secrets early.
49
49
  child.stdin.write(JSON.stringify({ operation, account, ...(bytes && { data: Buffer.from(bytes).toString('base64') }) }) + '\n');
50
- } else if (ready && !result && (Object.hasOwn(message, 'value') || message.error === 'BINDING_MISSING')) result = message;
50
+ } else if (ready && !result && (Object.hasOwn(message, 'value') || ['BINDING_MISSING', 'STORE_LOCKED', 'STORE_UNAVAILABLE'].includes(message.error))) result = message;
51
51
  else throw new Error();
52
52
  } catch { stop(); }
53
53
  }
@@ -62,9 +62,14 @@ export function nativeStoreOperation(operation, account, bytes, { directory = au
62
62
  try {
63
63
  if (failed || code !== 0 || !ready || !result || output) throw new Error();
64
64
  if (result.error === 'BINDING_MISSING') {
65
- reject(new AuthError('AUTH_STORE_UNAVAILABLE', 'The native credential-store binding could not load. Reinstall nansen-cli with optional dependencies enabled on a supported OS and architecture. See nansen doctor --offline and the browser-login platform guide.'));
65
+ reject(new AuthError('AUTH_STORE_UNAVAILABLE', `The native credential-store binding could not load. ${ENV_API_KEY_GUIDANCE} For saved browser login, reinstall nansen-cli with optional dependencies enabled on a supported OS and architecture. See docs/browser-login.md#preview-platform-scope.`));
66
66
  return;
67
67
  }
68
+ if (result.error === 'STORE_LOCKED') {
69
+ reject(new AuthError('AUTH_STORE_UNAVAILABLE', `The Linux Secret Service unlock prompt was dismissed or could not run in this terminal. Unlock the default collection using your provider's tools in the same user D-Bus session, then retry. Starting the service alone does not unlock it. See docs/browser-login.md#linux-secret-service-setup. ${ENV_API_KEY_GUIDANCE}`));
70
+ return;
71
+ }
72
+ if (result.error) { reject(unavailable()); return; }
68
73
  resolve(operation === 'get' && result.value !== null ? Buffer.from(result.value, 'base64') : result.value);
69
74
  } catch { reject(unavailable()); }
70
75
  });
package/src/bridge.js CHANGED
@@ -1918,13 +1918,15 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1918
1918
  log(` Type: ${execution_type}`);
1919
1919
  log(` Steps: ${steps.length}`);
1920
1920
 
1921
- // Dry-run preflight needs only the public address persisted alongside the
1922
- // quote. Prefer it before touching local wallet configuration; legacy
1923
- // quotes without the field retain the previous wallet-resolution path.
1924
- // A real execution always resolves the live signer independently and
1925
- // binds it to the quote before any credentials are loaded.
1921
+ // Dry-run preflight normally needs only the public address persisted with
1922
+ // the quote. Privy Hyperliquid quotes are the exception: resolve the live
1923
+ // signer so its wallet ID can be bound before even showing a preview.
1924
+ // Real execution always resolves the live signer independently and binds
1925
+ // it to the quote before any credentials are loaded.
1926
1926
  const quotedWalletAddress = validateQuotedWalletAddress(quoteId, quoteData.walletAddress);
1927
- const signer = guard.dryRun && quotedWalletAddress
1927
+ const requiresPrivyBinding = execution_type === 'hyperliquid_signature'
1928
+ && quoteData.walletProvider === 'privy';
1929
+ const signer = guard.dryRun && quotedWalletAddress && !requiresPrivyBinding
1928
1930
  ? null
1929
1931
  : resolveWalletAddress(walletName);
1930
1932
  const signerAddress = signer?.address || quotedWalletAddress;
@@ -1947,6 +1949,15 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1947
1949
  );
1948
1950
  }
1949
1951
 
1952
+ let privyBinding = null;
1953
+ if (execution_type === 'hyperliquid_signature' && signer?.provider === 'privy') {
1954
+ const { PrivyClient, assertPrivyWalletAddress } = await import('./privy.js');
1955
+ const client = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
1956
+ const walletId = signer.privyWalletIds?.evm;
1957
+ await assertPrivyWalletAddress(client, walletId, signer.address, 'evm');
1958
+ privyBinding = { client, walletId };
1959
+ }
1960
+
1950
1961
  // Re-screen the signer and any distinct recipient immediately before
1951
1962
  // signing. Quotes live up to an hour, and the EVM leg broadcasts directly.
1952
1963
  const screenAddresses = recipient
@@ -2106,14 +2117,12 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
2106
2117
  }
2107
2118
  } else if (execution_type === 'hyperliquid_signature') {
2108
2119
  if (creds.provider === 'privy') {
2109
- const { PrivyClient } = await import('./privy.js');
2110
- const privyClient = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
2111
2120
  for (const [index, step] of steps.entries()) {
2112
2121
  await processSignatureStepPrivy(step, {
2113
- privyClient,
2122
+ privyClient: privyBinding.client,
2114
2123
  // `signer` above — the same resolution that was screened and
2115
2124
  // matched against the quote, rather than resolving a second time.
2116
- walletId: signer.privyWalletIds?.evm,
2125
+ walletId: privyBinding.walletId,
2117
2126
  log,
2118
2127
  apiInstance,
2119
2128
  onBroadcast,