nansen-cli 1.46.0 → 2.0.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 (77) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +129 -14
  3. package/docs/browser-login.md +117 -0
  4. package/package.json +11 -2
  5. package/scripts/postinstall.js +35 -30
  6. package/skills/nansen-agent-guide/SKILL.md +13 -2
  7. package/skills/nansen-alerts-webhook-listener/SKILL.md +5 -2
  8. package/skills/nansen-dca-tracker/SKILL.md +10 -2
  9. package/skills/nansen-defi-positions/SKILL.md +5 -2
  10. package/skills/nansen-exit-signals/SKILL.md +10 -2
  11. package/skills/nansen-fund-tracker/SKILL.md +10 -2
  12. package/skills/nansen-general-search/SKILL.md +10 -2
  13. package/skills/nansen-holder-analysis/SKILL.md +10 -2
  14. package/skills/nansen-limit-orders/SKILL.md +6 -3
  15. package/skills/nansen-perp-screener/SKILL.md +10 -2
  16. package/skills/nansen-perp-trader-profile/SKILL.md +10 -2
  17. package/skills/nansen-polymarket-deep-dive/SKILL.md +10 -2
  18. package/skills/nansen-polymarket-insider-scan/SKILL.md +10 -2
  19. package/skills/nansen-polymarket-trader-profile/SKILL.md +10 -2
  20. package/skills/nansen-portfolio-tracker/SKILL.md +10 -2
  21. package/skills/nansen-prediction-markets/SKILL.md +10 -2
  22. package/skills/nansen-sm-cross-chain-flows/SKILL.md +10 -2
  23. package/skills/nansen-smart-alerts/SKILL.md +9 -4
  24. package/skills/nansen-smart-money-alpha/SKILL.md +10 -2
  25. package/skills/nansen-smart-money-tracker/SKILL.md +10 -2
  26. package/skills/nansen-smart-money-trend/SKILL.md +10 -2
  27. package/skills/nansen-token-research/SKILL.md +10 -2
  28. package/skills/nansen-token-screener/SKILL.md +14 -4
  29. package/skills/nansen-token-transfer-analysis/SKILL.md +10 -2
  30. package/skills/nansen-trading/SKILL.md +8 -2
  31. package/skills/nansen-wallet-batch/SKILL.md +10 -2
  32. package/skills/nansen-wallet-clustering/SKILL.md +10 -2
  33. package/skills/nansen-wallet-deep-dive/SKILL.md +10 -2
  34. package/skills/nansen-wallet-keychain-migration/SKILL.md +5 -2
  35. package/skills/nansen-wallet-manager/SKILL.md +11 -9
  36. package/skills/nansen-wallet-profiler/SKILL.md +10 -2
  37. package/skills/nansen-web-fetcher/SKILL.md +5 -2
  38. package/skills/nansen-web-searcher/SKILL.md +5 -2
  39. package/src/api.js +202 -104
  40. package/src/auth-browser.js +16 -0
  41. package/src/auth-credentials.js +73 -0
  42. package/src/auth-device.js +242 -0
  43. package/src/auth-key-input.js +46 -0
  44. package/src/auth-login.js +90 -0
  45. package/src/auth-state.js +487 -0
  46. package/src/auth-store-native.js +20 -0
  47. package/src/auth-store-worker.js +64 -0
  48. package/src/auth-store.js +140 -0
  49. package/src/auto-paginate.js +272 -0
  50. package/src/bridge.js +126 -21
  51. package/src/cache-inspect.js +345 -0
  52. package/src/cli.js +470 -197
  53. package/src/commands/agent.js +15 -7
  54. package/src/commands/completion.js +2 -15
  55. package/src/commands/mcp.js +20 -18
  56. package/src/cost-cache.js +16 -2
  57. package/src/debug.js +348 -0
  58. package/src/doctor.js +22 -45
  59. package/src/hl-action.js +41 -13
  60. package/src/mcp-client-config.js +169 -0
  61. package/src/mcp-client-config.json +17 -0
  62. package/src/mcp-verify.js +6 -5
  63. package/src/perp.js +41 -0
  64. package/src/privy.js +12 -12
  65. package/src/response-meta.js +56 -1
  66. package/src/rpc-urls.js +9 -11
  67. package/src/schema.json +185 -8
  68. package/src/semver.js +23 -4
  69. package/src/swap-simulation.js +35 -30
  70. package/src/telemetry.js +20 -0
  71. package/src/trading.js +266 -29
  72. package/src/transfer.js +53 -6
  73. package/src/update-check.js +9 -1
  74. package/src/wallet.js +107 -17
  75. package/src/walletconnect-trading.js +24 -5
  76. package/src/x402-svm.js +123 -64
  77. package/src/x402.js +46 -14
package/src/api.js CHANGED
@@ -4,11 +4,15 @@
4
4
  */
5
5
 
6
6
  import fs from 'fs';
7
+ import { authConfigView, resolveCredential, assertUsableSelection, AuthError } from './auth-credentials.js';
8
+ import { createAuthState } from './auth-state.js';
9
+ import { validateSession } from './auth-device.js';
7
10
  import path from 'path';
8
11
  import { fileURLToPath } from 'url';
9
12
  import { EVM_CHAINS } from './chain-ids.js';
10
13
  import { getAnonymousId, TELEMETRY_DISABLED } from './telemetry.js';
11
14
  import { readResponseMeta, stringHeader } from './response-meta.js';
15
+ import { trace, traceRequest, traceResponse, traceError, traceRetry, traceCacheHit } from './debug.js';
12
16
 
13
17
  /**
14
18
  * Key for the credit/rate-limit metadata attached to a successful response.
@@ -178,6 +182,25 @@ export const SERVER_CODE_MAP = {
178
182
  invalid_params: ErrorCode.INVALID_PARAMS,
179
183
  };
180
184
 
185
+ export function browserSessionError(status, data = {}) {
186
+ const raw = data?.error_code ?? data?.code ?? data?.detail?.error_code ?? data?.detail?.code;
187
+ const category = status === 403 ? (raw === 'insufficient_credits' ? ErrorCode.CREDITS_EXHAUSTED : raw === 'plan_upgrade_required' ? ErrorCode.PLAN_UPGRADE_REQUIRED : undefined) : undefined;
188
+ const code = category || statusToErrorCode(status);
189
+ const message = code === ErrorCode.CREDITS_EXHAUSTED
190
+ ? 'Insufficient API credits for the selected account. Top up at https://app.nansen.ai/api?tab=api. No payment was attempted.'
191
+ : code === ErrorCode.PLAN_UPGRADE_REQUIRED ? 'The selected account plan does not include this endpoint. Check upgrade options at https://app.nansen.ai/api?tab=api.'
192
+ : status === 401 ? 'The selected browser session was rejected. Run: nansen login.'
193
+ : status === 503 ? 'API authentication is temporarily unavailable. Retry later.'
194
+ : `API request failed (${status}). The selected account was not changed and no payment was attempted.`;
195
+ return { code, message };
196
+ }
197
+
198
+ export function browserSessionResponseMeta(response) {
199
+ const meta = readResponseMeta(response);
200
+ // Only bounded numeric quota metadata is safe to echo from an auth error.
201
+ return { ...(meta?.credits && { credits: meta.credits }), ...(meta?.rateLimit && { rateLimit: meta.rateLimit }) };
202
+ }
203
+
181
204
  /**
182
205
  * Map an error response to an error code.
183
206
  *
@@ -264,31 +287,11 @@ export function getConfigFile() {
264
287
  return CONFIG_FILE;
265
288
  }
266
289
 
267
- /**
268
- * Save config to ~/.nansen/config.json
269
- */
270
- export function saveConfig(config) {
271
- if (!fs.existsSync(CONFIG_DIR)) {
272
- fs.mkdirSync(CONFIG_DIR, { mode: 0o700, recursive: true });
273
- }
274
- fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), { mode: 0o600 });
275
- }
276
-
277
- /**
278
- * Delete config file (logout)
279
- */
280
- export function deleteConfig() {
281
- if (fs.existsSync(CONFIG_FILE)) {
282
- fs.unlinkSync(CONFIG_FILE);
283
- return true;
284
- }
285
- return false;
286
- }
287
-
288
290
  // ============= Response Cache =============
289
291
 
290
292
  const CACHE_DIR = path.join(CONFIG_DIR, 'cache');
291
- const DEFAULT_CACHE_TTL = 300; // 5 minutes
293
+ // Exported so the cache inspector reports the same default TTL the client applies.
294
+ export const DEFAULT_CACHE_TTL = 300; // 5 minutes
292
295
 
293
296
  import crypto from 'crypto';
294
297
 
@@ -349,8 +352,8 @@ export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL
349
352
  const cached = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
350
353
  const age = (Date.now() - cached.timestamp) / 1000;
351
354
 
352
- if (ttlSeconds <= 0 || age > ttlSeconds) {
353
- // Cache expired or TTL is 0, delete it
355
+ if (!Number.isFinite(cached.timestamp) || ttlSeconds <= 0 || age > ttlSeconds) {
356
+ // Delete entries with invalid timestamps, expired entries, or disabled entries.
354
357
  fs.unlinkSync(cacheFile);
355
358
  return null;
356
359
  }
@@ -587,44 +590,10 @@ function classifyAutoDetectedAddress(address) {
587
590
  }
588
591
 
589
592
  export function loadConfig() {
590
- // Base config from files, then env vars override individual fields
591
- let config = null;
592
-
593
- // ~/.nansen/config.json (from `nansen login`)
594
- if (fs.existsSync(CONFIG_FILE)) {
595
- try { config = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8')); } catch (_e) { /* ignore */ }
596
- }
597
-
598
- // Local config.json (for development)
599
- if (!config) {
600
- const localConfig = path.join(__dirname, '..', 'config.json');
601
- if (fs.existsSync(localConfig)) {
602
- config = JSON.parse(fs.readFileSync(localConfig, 'utf8'));
603
- }
604
- }
605
-
606
- if (!config) {
607
- config = { apiKey: null, baseUrl: 'https://api.nansen.ai' };
608
- }
609
-
610
- // Ensure baseUrl default (config file from older versions may omit it)
611
- if (!config.baseUrl) {
612
- config.baseUrl = 'https://api.nansen.ai';
613
- }
614
-
615
- // Env vars override individual fields
616
- if (process.env.NANSEN_API_KEY) {
617
- config.apiKey = process.env.NANSEN_API_KEY;
618
- }
619
- if (process.env.NANSEN_BASE_URL) {
620
- config.baseUrl = process.env.NANSEN_BASE_URL;
621
- }
622
-
623
- return config;
593
+ const view = authConfigView();
594
+ return { ...view.config, apiKey: view.apiKey, baseUrl: view.baseUrl };
624
595
  }
625
596
 
626
- const config = loadConfig();
627
-
628
597
  // ============= Retry Configuration =============
629
598
 
630
599
  const DEFAULT_RETRY_OPTIONS = {
@@ -706,6 +675,20 @@ function parseRetryAfter(headerValue) {
706
675
  return null;
707
676
  }
708
677
 
678
+ /**
679
+ * Server-side request id for a response, or null when it carries none.
680
+ * Read straight off the header so the debug trace can name the id on every
681
+ * attempt without paying for a full metadata parse. Tolerates any header bag
682
+ * with a .get() — a real Headers, or a Map in tests.
683
+ */
684
+ function requestIdOf(response) {
685
+ try {
686
+ return response?.headers?.get?.('x-request-id') ?? null;
687
+ } catch {
688
+ return null;
689
+ }
690
+ }
691
+
709
692
  /**
710
693
  * Build a date range from today back N days
711
694
  * @param {number} days - Number of days back from today
@@ -718,9 +701,14 @@ export function buildDateRange(days) {
718
701
  }
719
702
 
720
703
  export class NansenAPI {
721
- constructor(apiKey = config.apiKey, baseUrl = config.baseUrl, options = {}) {
722
- this.apiKey = apiKey || null;
723
- this.baseUrl = baseUrl;
704
+ constructor(apiKey = undefined, baseUrl = undefined, options = {}) {
705
+ const view = authConfigView();
706
+ this.selection = options.credential || resolveCredential({ explicitKey: apiKey, snapshot: view });
707
+ this.apiKey = this.selection.kind === 'api-key' ? this.selection.apiKey : null;
708
+ this.baseUrl = baseUrl ?? view.baseUrl;
709
+ this.authState = options.authState;
710
+ this.allowPayment = options.allowPayment !== false;
711
+ this.redactAuthDiagnostics = options.redactAuthDiagnostics === true;
724
712
  this.retryOptions = { ...DEFAULT_RETRY_OPTIONS, ...options.retry };
725
713
  this.cacheOptions = {
726
714
  enabled: options.cache?.enabled ?? false,
@@ -736,6 +724,16 @@ export class NansenAPI {
736
724
  * low-credit warning wants.
737
725
  */
738
726
  this.lastResponseMeta = null;
727
+ /** Live response objects carry RESPONSE_META, allowing request-local attribution. */
728
+ this.responseMetadataOnPayload = true;
729
+ /**
730
+ * Command-level aggregate populated only by the auto-pagination wrapper.
731
+ * lastResponseMeta above deliberately remains the metadata for the final
732
+ * individual response.
733
+ */
734
+ this.paginatedResponseMeta = null;
735
+ /** API path paired with paginatedResponseMeta for fallback cost estimates. */
736
+ this.paginatedEndpoint = null;
739
737
  /** API path of the most recent request(), for pairing lastResponseMeta with a cost estimate. */
740
738
  this.lastEndpoint = null;
741
739
  /**
@@ -751,6 +749,19 @@ export class NansenAPI {
751
749
  this.servedFromCache = false;
752
750
  }
753
751
 
752
+ async requestCredentials(extraHeaders = this.defaultHeaders) {
753
+ assertUsableSelection(this.selection);
754
+ if (this.selection.kind === 'session') {
755
+ if (Object.keys(extraHeaders || {}).some(k => ['apikey', 'authorization', 'payment-signature'].includes(k.toLowerCase()))) throw new AuthError('MIXED_CREDENTIALS', 'Send the selected browser session alone.');
756
+ const bundle = await (this.authState || (this.authState = createAuthState())).acquireSession(this.selection, { audience: this.baseUrl });
757
+ validateSession(bundle);
758
+ if (bundle.audience !== this.baseUrl || bundle.accountId !== this.selection.accountId || bundle.issuer !== this.selection.issuer) throw new AuthError('AUTH_ORIGIN_MISMATCH', 'The saved session does not match the selected API origin/account. Check NANSEN_BASE_URL or run nansen login.');
759
+ this.selection = { ...this.selection, generation: bundle.generation, expiresAt: bundle.expiresAt };
760
+ return { Authorization: `Bearer ${bundle.accessToken}` };
761
+ }
762
+ return this.apiKey ? { apikey: this.apiKey } : {};
763
+ }
764
+
754
765
  static cleanBody(body) {
755
766
  return Object.fromEntries(
756
767
  Object.entries(body).filter(([_, v]) =>
@@ -766,7 +777,7 @@ export class NansenAPI {
766
777
  * sentinel if the server cleanly, legibly rejected it without settling.
767
778
  * Throws a NansenError(PAYMENT_AMBIGUOUS) — instead of returning the sentinel —
768
779
  * for any outcome that doesn't prove the payment was rejected: a transport
769
- * failure after transmission, an HTTP 5xx, or a response body that can't be
780
+ * failure after transmission, an admission denial, an HTTP 5xx, or a response body that can't be
770
781
  * parsed. In all of those cases the server may already have received and
771
782
  * settled the payment, so the caller must not treat it as safe to retry with
772
783
  * a different option — that would risk paying twice for the same request.
@@ -790,6 +801,12 @@ export class NansenAPI {
790
801
  const method = options.method || 'POST';
791
802
  const isGet = method === 'GET';
792
803
  let paidResponse;
804
+ const startedAt = Date.now();
805
+ // The signature itself is never traced — only that a paid retry went out.
806
+ // As in the legacy key flow, payment authenticates this retry on its own.
807
+ // Do not attach requestCredentials(): Bearer plus payment is rejected by API
808
+ // admission, and neither this retry nor its result changes saved selection.
809
+ traceRequest({ method, url, attempt: 1, payment: 'x402' });
793
810
  try {
794
811
  paidResponse = await fetch(url, {
795
812
  method,
@@ -806,6 +823,7 @@ export class NansenAPI {
806
823
  ...(!isGet && method !== 'DELETE' && { body: JSON.stringify(NansenAPI.cleanBody(body)) }),
807
824
  });
808
825
  } catch (err) {
826
+ traceError({ method, url, durationMs: Date.now() - startedAt, attempt: 1, error: err.message });
809
827
  // The signature was already on the wire when the connection failed —
810
828
  // the server may have received and settled it before we lost the
811
829
  // response. Fail closed rather than let the caller sign and send a
@@ -815,7 +833,26 @@ export class NansenAPI {
815
833
  ErrorCode.PAYMENT_AMBIGUOUS,
816
834
  );
817
835
  }
836
+ // fetch resolves when response headers are available, before body parsing;
837
+ // duration_ms therefore reports time-to-headers (TTFB), not full download.
838
+ traceResponse({
839
+ method,
840
+ url,
841
+ status: paidResponse.status,
842
+ durationMs: Date.now() - startedAt,
843
+ requestId: requestIdOf(paidResponse),
844
+ attempt: 1,
845
+ payment: 'x402',
846
+ });
818
847
  if (!paidResponse.ok) {
848
+ // An admission denial does not prove that a transmitted payment cannot
849
+ // settle. Stop here instead of authorizing another rail or wallet.
850
+ if ([401, 403, 429, 451].includes(paidResponse.status)) {
851
+ throw new NansenError(
852
+ `x402 payment outcome unknown: paid request was denied (${paidResponse.status}). Not attempting another payment for the same request.`,
853
+ ErrorCode.PAYMENT_AMBIGUOUS,
854
+ );
855
+ }
819
856
  // A 5xx doesn't prove the payment was rejected — the server could have
820
857
  // processed it before failing to respond. Only a readable non-5xx
821
858
  // rejection body is safe to treat as "try the next option".
@@ -867,6 +904,13 @@ export class NansenAPI {
867
904
 
868
905
  async request(endpoint, body = {}, options = {}) {
869
906
  this.lastEndpoint = endpoint;
907
+ const extraHeaders = { ...this.defaultHeaders, ...options.headers };
908
+ let credentialHeaders = await this.requestCredentials(extraHeaders);
909
+ // Keys and browser sessions share the same payment policy. Explicit raw
910
+ // authentication headers still cannot be forwarded into a payment retry.
911
+ // Either the instance or this request can disable automatic payment;
912
+ // a request cannot re-enable it when the instance has disabled it.
913
+ const mayAutoPay = this.allowPayment && options.allowPayment !== false && !Object.keys(extraHeaders).some(k => ['apikey', 'authorization'].includes(k.toLowerCase()));
870
914
  const url = `${this.baseUrl}${endpoint}`;
871
915
  const { maxRetries, baseDelayMs, maxDelayMs, maxRetryAfterMs, retryOnStatus } = this.retryOptions;
872
916
  const shouldRetry = options.retry !== false; // Allow disabling retry per-request
@@ -879,18 +923,20 @@ export class NansenAPI {
879
923
  // cacheContext is therefore null unless caching is on; the `&& cacheContext`
880
924
  // guards below ensure that null never reaches getCacheKey, where a missing
881
925
  // identity would silently produce a credential-agnostic (shared) cache key.
882
- const cacheContext = useCache
926
+ const credentialContext = () => useCache
883
927
  ? {
884
- baseUrl: this.baseUrl,
928
+ baseUrl: `${this.baseUrl}#${this.selection.generation || ""}`,
885
929
  method,
886
- identity: computeIdentityDigest(this.apiKey, this.defaultHeaders, options.headers),
930
+ identity: computeIdentityDigest(this.apiKey, credentialHeaders, this.defaultHeaders, options.headers),
887
931
  }
888
932
  : null;
889
933
 
934
+ let cacheContext = credentialContext();
890
935
  if (useCache && cacheContext) {
891
936
  const cached = getCachedResponse(endpoint, body, cacheTtl, cacheContext);
892
937
  if (cached) {
893
938
  this.servedFromCache = true;
939
+ traceCacheHit({ method, url });
894
940
  return cached;
895
941
  }
896
942
  }
@@ -898,8 +944,20 @@ export class NansenAPI {
898
944
 
899
945
  let lastError;
900
946
 
901
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
947
+ const maxAttempts = (shouldRetry ? maxRetries : 0) + 1;
948
+
949
+ // Bound the loop by the displayed attempt count so retry:false can never
950
+ // produce a trace such as attempt=2/1, even if a future branch continues.
951
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
952
+ // Backoff may cross expiry or a competing rotation/logout. Reacquire
953
+ // before dispatch, outside the resource network-error retry handler.
954
+ if (this.selection.kind === 'session' && (attempt > 0 || this.selection.expiresAt <= Date.now())) {
955
+ credentialHeaders = await this.requestCredentials(extraHeaders);
956
+ cacheContext = credentialContext();
957
+ }
902
958
  let response;
959
+ const startedAt = Date.now();
960
+ traceRequest({ method, url, attempt: attempt + 1, maxAttempts });
903
961
  try {
904
962
  const isGet = method === 'GET';
905
963
  response = await fetch(url, {
@@ -910,7 +968,7 @@ export class NansenAPI {
910
968
  'X-Client-Type': 'nansen-cli',
911
969
  'X-Client-Version': packageVersion,
912
970
  ...telemetryHeaders(),
913
- ...(this.apiKey ? { 'apikey': this.apiKey } : {}),
971
+ ...credentialHeaders,
914
972
  ...this.defaultHeaders,
915
973
  ...options.headers
916
974
  },
@@ -918,27 +976,40 @@ export class NansenAPI {
918
976
  });
919
977
  } catch (err) {
920
978
  // Network-level errors - retry these too
979
+ traceError({ method, url, durationMs: Date.now() - startedAt, attempt: attempt + 1, error: this.redactAuthDiagnostics ? 'API request failed' : err.message });
921
980
  lastError = new NansenError(
922
- `Network error: ${err.message}`,
981
+ this.selection.kind === 'session' ? 'API request failed. Check your connection and retry.' : `Network error: ${err.message}`,
923
982
  ErrorCode.NETWORK_ERROR,
924
983
  null,
925
- { originalError: err.message, attempt: attempt + 1 }
984
+ { ...(this.selection.kind !== 'session' && { originalError: err.message }), attempt: attempt + 1 }
926
985
  );
927
-
986
+
928
987
  if (shouldRetry && attempt < maxRetries) {
929
988
  const delayMs = calculateBackoff(attempt, baseDelayMs, maxDelayMs);
989
+ traceRetry({ method, url, attempt: attempt + 1, reason: 'network-error', delayMs });
930
990
  await sleep(delayMs);
931
991
  continue;
932
992
  }
933
993
  throw lastError;
934
994
  }
935
995
 
996
+ // Keep response timing independent of body size: this is elapsed time to
997
+ // response headers (TTFB), before readBody downloads/parses the payload.
998
+ traceResponse({
999
+ method,
1000
+ url,
1001
+ status: response.status,
1002
+ durationMs: Date.now() - startedAt,
1003
+ requestId: this.redactAuthDiagnostics ? undefined : requestIdOf(response),
1004
+ attempt: attempt + 1,
1005
+ });
1006
+
936
1007
  let data;
937
1008
  try {
938
1009
  data = await readBody(response);
939
1010
  } catch (err) {
940
1011
  // Non-JSON response (rare, usually server errors)
941
- const meta = readResponseMeta(response);
1012
+ const meta = this.selection.kind === 'session' ? browserSessionResponseMeta(response) : readResponseMeta(response);
942
1013
  this.lastResponseMeta = meta;
943
1014
  // readBody already holds the text when the server declared a non-JSON
944
1015
  // body; otherwise try to read it now (null once json() consumed it).
@@ -949,7 +1020,7 @@ export class NansenAPI {
949
1020
  statusToErrorCode(response.status, {}),
950
1021
  response.status,
951
1022
  {
952
- body: rawBody,
1023
+ ...(this.selection.kind !== 'session' && { body: rawBody }),
953
1024
  attempt: attempt + 1,
954
1025
  retryAfterMs,
955
1026
  ...(meta?.requestId && { requestId: meta.requestId })
@@ -960,6 +1031,7 @@ export class NansenAPI {
960
1031
  // that answers in plain text or HTML is still a 429/5xx.
961
1032
  if (shouldRetry && attempt < maxRetries && retryOnStatus.includes(response.status)) {
962
1033
  const delayMs = calculateBackoff(attempt, baseDelayMs, maxDelayMs, retryAfterMs);
1034
+ traceRetry({ method, url, status: response.status, attempt: attempt + 1, reason: 'unparseable-response', delayMs, retryAfterMs });
963
1035
  await sleep(delayMs);
964
1036
  lastError = error;
965
1037
  continue;
@@ -977,21 +1049,43 @@ export class NansenAPI {
977
1049
  // an apostrophe inside the message (e.g. "can't") doesn't truncate it.
978
1050
  const nestedMatch = typeof message === 'string' && message.match(/['"]message['"]\s*:\s*['"](.*?)['"]\s*[,}]/s);
979
1051
  if (nestedMatch) message = nestedMatch[1];
980
- const code = statusToErrorCode(response.status, data);
1052
+ const safeSessionError = this.selection.kind === 'session' ? browserSessionError(response.status, data) : null;
1053
+ const code = safeSessionError?.code || statusToErrorCode(response.status, data);
1054
+ // Keep a body-only challenge available to the signer without exposing
1055
+ // the authenticated error body through browser-session diagnostics.
1056
+ const bodyPaymentRequirements = response.status === 402 ? data.paymentRequirements : undefined;
981
1057
  const retryAfterMs = parseRetryAfter(response.headers.get('retry-after'));
1058
+ if (this.selection.kind === 'session') {
1059
+ message = safeSessionError.message;
1060
+ data = {}; // Authenticated errors must not echo access tokens into output.
1061
+ }
982
1062
 
983
1063
  // Enhance messages for specific error codes
984
1064
  if (code === ErrorCode.UNAUTHORIZED) {
985
- message = this.apiKey ? message : 'Not logged in. Run: nansen login';
1065
+ message = this.apiKey || safeSessionError ? message : 'Not logged in. Run: nansen login';
986
1066
  } else if (code === ErrorCode.UNSUPPORTED_FILTER) {
987
1067
  message = message.replace(/\.+$/, '') + '. This filter is not supported for this token/chain combination. Do not retry.';
988
1068
  } else if (code === ErrorCode.CREDITS_EXHAUSTED) {
989
1069
  message = message.replace(/\.+$/, '') + '. No retry will help. Check your Nansen dashboard for credit balance.';
990
- } else if (code === ErrorCode.PAYMENT_REQUIRED) {
1070
+ } else if (code === ErrorCode.PAYMENT_REQUIRED && response.status === 402) {
991
1071
  // Try x402 auto-payment: local wallet (with network fallback), then WalletConnect
992
- const hasManualSignature = !!(this.defaultHeaders['Payment-Signature'] || options.headers?.['Payment-Signature']);
1072
+ const hasManualSignature = Object.keys(extraHeaders).some(k => k.toLowerCase() === 'payment-signature');
1073
+ // Session and API-key clients receive credential-specific guidance.
1074
+ if (safeSessionError && mayAutoPay) {
1075
+ message = 'Payment required (x402). Configure and fund a supported wallet, or top up the selected account.';
1076
+ } else if (this.selection.kind === 'api-key' && !hasManualSignature) {
1077
+ message = 'Payment required (x402). Configure and fund a supported wallet, top up the selected account, or explicitly provide --x402-payment-signature.';
1078
+ }
1079
+
1080
+ if (this.selection.kind === 'api-key' && !hasManualSignature) {
1081
+ const paymentHeader = response.headers.get('payment-required');
1082
+ if (paymentHeader) {
1083
+ try { data.paymentRequirements = JSON.parse(Buffer.from(paymentHeader, 'base64').toString('utf8')); }
1084
+ catch { /* An invalid challenge must not trigger signing or retry. */ }
1085
+ }
1086
+ }
993
1087
 
994
- if (!hasManualSignature) {
1088
+ if (mayAutoPay && !hasManualSignature) {
995
1089
  // Determine payment method from default wallet's provider
996
1090
  let defaultWalletProvider = 'local';
997
1091
  let defaultWalletName = 'unknown';
@@ -1004,7 +1098,7 @@ export class NansenAPI {
1004
1098
  defaultWalletProvider = wallet.provider || 'local';
1005
1099
  }
1006
1100
  } catch (err) {
1007
- if (process.env.DEBUG) console.error(`[x402] Failed to detect wallet provider: ${err.message}`);
1101
+ trace('x402.wallet_provider_lookup_failed', { error: err.message });
1008
1102
  }
1009
1103
 
1010
1104
  if (defaultWalletProvider === 'privy') {
@@ -1021,7 +1115,7 @@ export class NansenAPI {
1021
1115
  // treated as an ordinary payment failure — there is no other
1022
1116
  // provider to fall back to here, and retrying could double-pay.
1023
1117
  if (privyErr instanceof NansenError && privyErr.code === ErrorCode.PAYMENT_AMBIGUOUS) throw privyErr;
1024
- message = `x402 Privy payment failed: ${privyErr.message}`;
1118
+ message = safeSessionError ? 'x402 Privy payment failed. Check the wallet configuration and balance.' : `x402 Privy payment failed: ${privyErr.message}`;
1025
1119
  }
1026
1120
  } else {
1027
1121
  // Local wallet or no wallet: existing local wallet + WalletConnect flow
@@ -1050,11 +1144,11 @@ export class NansenAPI {
1050
1144
  try {
1051
1145
  paymentRequirements = JSON.parse(Buffer.from(paymentHeader, 'base64').toString('utf8'));
1052
1146
  } catch {
1053
- data.paymentRequiredRaw = paymentHeader;
1147
+ if (!safeSessionError) data.paymentRequiredRaw = paymentHeader;
1054
1148
  }
1055
1149
  }
1056
- if (!paymentRequirements && data.paymentRequirements) {
1057
- paymentRequirements = data.paymentRequirements;
1150
+ if (!paymentRequirements && bodyPaymentRequirements) {
1151
+ paymentRequirements = bodyPaymentRequirements;
1058
1152
  }
1059
1153
 
1060
1154
  if (paymentRequirements) {
@@ -1069,24 +1163,19 @@ export class NansenAPI {
1069
1163
  // ordinary "payment failed" that invites the caller to
1070
1164
  // retry the whole request (and sign yet another payment).
1071
1165
  if (x402Err instanceof NansenError && x402Err.code === ErrorCode.PAYMENT_AMBIGUOUS) throw x402Err;
1072
- if (!this.apiKey) {
1073
- message = 'No API key configured. Three ways to authenticate:\n' +
1074
- ' 1. API key: run `nansen login --human` or set NANSEN_API_KEY (get key at https://app.nansen.ai/auth/agent-setup)\n' +
1075
- ' 2. x402 micropayment: nansen wallet create + fund with USDC on Base/Solana or USDT0 on X Layer (no API key needed)\n' +
1076
- ' 3. MPP via tempo: install tempo CLI, run `tempo wallet login`, then call the API with `tempo request` (see skills/nansen-mpp-payment)';
1077
- } else {
1078
- message = `x402 auto-payment failed: ${x402Err.message}`;
1079
- }
1080
- }
1081
- if (this.apiKey) {
1082
- data.paymentRequirements = paymentRequirements;
1166
+ message = this.selection.kind !== 'anonymous'
1167
+ ? 'x402 wallet payment failed. Check the wallet configuration and balance, or top up the selected account.'
1168
+ : 'No API key configured. Three ways to authenticate:\n' +
1169
+ ' 1. API key: run `nansen login --human` or set NANSEN_API_KEY (get key at https://app.nansen.ai/auth/agent-setup)\n' +
1170
+ ' 2. x402 micropayment: nansen wallet create + fund with USDC on Base/Solana or USDT0 on X Layer (no API key needed)\n' +
1171
+ ' 3. MPP via tempo: install tempo CLI, run `tempo wallet login`, then call the API with `tempo request` (see skills/nansen-mpp-payment)';
1083
1172
  }
1084
1173
  }
1085
1174
  }
1086
1175
  }
1087
1176
  }
1088
1177
 
1089
- if (!message || message === data.message) {
1178
+ if ((mayAutoPay || hasManualSignature) && (!message || message === data.message)) {
1090
1179
  message = 'Payment required (x402). Sign the paymentRequirements below per https://docs.x402.org and pass the result with --x402-payment-signature <value>.';
1091
1180
  }
1092
1181
  }
@@ -1099,7 +1188,7 @@ export class NansenAPI {
1099
1188
  // On a retried call this is the LAST attempt's id — each attempt gets
1100
1189
  // its own server-side id, and the last one is the failure worth
1101
1190
  // reporting.
1102
- const meta = readResponseMeta(response);
1191
+ const meta = this.selection.kind === 'session' ? browserSessionResponseMeta(response) : readResponseMeta(response);
1103
1192
  this.lastResponseMeta = meta;
1104
1193
  lastError = new NansenError(message, code, response.status, {
1105
1194
  ...data,
@@ -1122,6 +1211,15 @@ export class NansenAPI {
1122
1211
  ? retryAfterMs
1123
1212
  : Math.min(retryAfterMs, maxDelayMs);
1124
1213
  const delayMs = calculateBackoff(attempt, baseDelayMs, maxDelayMs, serverDelayMs);
1214
+ traceRetry({
1215
+ method,
1216
+ url,
1217
+ status: response.status,
1218
+ attempt: attempt + 1,
1219
+ reason: retryAfterMs ? 'retry-after' : 'retryable-status',
1220
+ delayMs,
1221
+ retryAfterMs,
1222
+ });
1125
1223
  await sleep(delayMs);
1126
1224
  continue;
1127
1225
  }
@@ -1158,7 +1256,7 @@ export class NansenAPI {
1158
1256
  // ============= Account Endpoint =============
1159
1257
 
1160
1258
  async getAccount() {
1161
- return this.request('/api/v1/account', {}, { method: 'GET', cache: false });
1259
+ return this.request('/api/v1/account', {}, { method: 'GET', cache: false, allowPayment: false });
1162
1260
  }
1163
1261
 
1164
1262
  // ============= Chain Endpoints =============
@@ -1260,13 +1358,13 @@ export class NansenAPI {
1260
1358
  }
1261
1359
 
1262
1360
  async addressLabels(params = {}) {
1263
- const { address, chain = 'ethereum', pagination = { page: 1, per_page: 100 } } = params;
1361
+ const { address, chain = 'ethereum', pagination = { page: 1, per_page: 100 }, requestOptions } = params;
1264
1362
  if (address) requireValidAddress(address, chain);
1265
1363
  return this.request('/api/v1/profiler/address/labels', {
1266
1364
  address,
1267
1365
  chain,
1268
1366
  pagination
1269
- });
1367
+ }, requestOptions);
1270
1368
  }
1271
1369
 
1272
1370
  async addressPremiumLabels(params = {}) {
@@ -1294,7 +1392,7 @@ export class NansenAPI {
1294
1392
  }
1295
1393
 
1296
1394
  async addressPnl(params = {}) {
1297
- const { address, chain = 'ethereum', date, days = 30, filters = {}, orderBy, pagination } = params;
1395
+ const { address, chain = 'ethereum', date, days = 30, filters = {}, orderBy, pagination, requestOptions } = params;
1298
1396
  if (address) requireValidAddress(address, chain);
1299
1397
  const dateRange = date || buildDateRange(days);
1300
1398
  return this.request('/api/v1/profiler/address/pnl', {
@@ -1304,7 +1402,7 @@ export class NansenAPI {
1304
1402
  filters,
1305
1403
  order_by: orderBy,
1306
1404
  pagination
1307
- });
1405
+ }, requestOptions);
1308
1406
  }
1309
1407
 
1310
1408
  async entitySearch(params = {}) {
@@ -1393,7 +1491,7 @@ export class NansenAPI {
1393
1491
  }
1394
1492
 
1395
1493
  async addressCounterparties(params = {}) {
1396
- const { address, chain = 'ethereum', filters = {}, orderBy, pagination, days = 30 } = params;
1494
+ const { address, chain = 'ethereum', filters = {}, orderBy, pagination, days = 30, requestOptions } = params;
1397
1495
  if (address) requireValidAddress(address, chain);
1398
1496
  return this.request('/api/v1/profiler/address/counterparties', {
1399
1497
  address,
@@ -1402,7 +1500,7 @@ export class NansenAPI {
1402
1500
  filters,
1403
1501
  order_by: orderBy,
1404
1502
  pagination
1405
- });
1503
+ }, requestOptions);
1406
1504
  }
1407
1505
 
1408
1506
  /**
@@ -0,0 +1,16 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { trustedIssuer } from './auth-credentials.js';
3
+ export function openAuthBrowser(url, audience, { platform = process.platform, spawnFn = spawn } = {}) {
4
+ const parsed = new URL(url);
5
+ if (parsed.origin !== trustedIssuer(audience) || parsed.pathname !== '/device' || parsed.username || parsed.password || parsed.hash || [...parsed.searchParams.keys()].some(k => k !== 'user_code')) throw new Error('Untrusted verification URL');
6
+ const executable = platform === 'darwin' ? '/usr/bin/open' : platform === 'win32' ? 'powershell.exe' : 'xdg-open';
7
+ const args = platform === 'win32' ? ['-NoProfile', '-NonInteractive', '-Command', '$u = [Console]::In.ReadToEnd(); Start-Process -FilePath $u'] : [url];
8
+ return new Promise(resolve => {
9
+ const child = spawnFn(executable, args, { shell: false, windowsHide: true, stdio: ['pipe', 'ignore', 'ignore'] });
10
+ const timer = setTimeout(() => child.kill('SIGKILL'), 5000);
11
+ child.stdin.on('error', () => {});
12
+ child.stdin.end(platform === 'win32' ? url : '');
13
+ child.on('error', () => { clearTimeout(timer); resolve(false); });
14
+ child.on('close', code => { clearTimeout(timer); resolve(code === 0); });
15
+ });
16
+ }