nansen-cli 1.45.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.
- package/CHANGELOG.md +172 -0
- package/README.md +158 -18
- package/docs/browser-login.md +117 -0
- package/package.json +11 -2
- package/scripts/postinstall.js +35 -30
- package/skills/nansen-agent-guide/SKILL.md +13 -2
- package/skills/nansen-alerts-webhook-listener/SKILL.md +5 -2
- package/skills/nansen-dca-tracker/SKILL.md +10 -2
- package/skills/nansen-defi-positions/SKILL.md +5 -2
- package/skills/nansen-exit-signals/SKILL.md +10 -2
- package/skills/nansen-fund-tracker/SKILL.md +10 -2
- package/skills/nansen-general-search/SKILL.md +10 -2
- package/skills/nansen-holder-analysis/SKILL.md +10 -2
- package/skills/nansen-limit-orders/SKILL.md +6 -3
- package/skills/nansen-perp-screener/SKILL.md +10 -2
- package/skills/nansen-perp-trader-profile/SKILL.md +10 -2
- package/skills/nansen-polymarket-deep-dive/SKILL.md +10 -2
- package/skills/nansen-polymarket-insider-scan/SKILL.md +10 -2
- package/skills/nansen-polymarket-trader-profile/SKILL.md +10 -2
- package/skills/nansen-portfolio-tracker/SKILL.md +10 -2
- package/skills/nansen-prediction-markets/SKILL.md +10 -2
- package/skills/nansen-sm-cross-chain-flows/SKILL.md +10 -2
- package/skills/nansen-smart-alerts/SKILL.md +9 -4
- package/skills/nansen-smart-money-alpha/SKILL.md +10 -2
- package/skills/nansen-smart-money-tracker/SKILL.md +10 -2
- package/skills/nansen-smart-money-trend/SKILL.md +10 -2
- package/skills/nansen-token-research/SKILL.md +10 -2
- package/skills/nansen-token-screener/SKILL.md +14 -4
- package/skills/nansen-token-transfer-analysis/SKILL.md +10 -2
- package/skills/nansen-trading/SKILL.md +27 -2
- package/skills/nansen-wallet-batch/SKILL.md +10 -2
- package/skills/nansen-wallet-clustering/SKILL.md +10 -2
- package/skills/nansen-wallet-deep-dive/SKILL.md +10 -2
- package/skills/nansen-wallet-keychain-migration/SKILL.md +23 -15
- package/skills/nansen-wallet-manager/SKILL.md +26 -10
- package/skills/nansen-wallet-profiler/SKILL.md +10 -2
- package/skills/nansen-web-fetcher/SKILL.md +5 -2
- package/skills/nansen-web-searcher/SKILL.md +5 -2
- package/src/api.js +319 -129
- package/src/auth-browser.js +16 -0
- package/src/auth-credentials.js +73 -0
- package/src/auth-device.js +242 -0
- package/src/auth-key-input.js +46 -0
- package/src/auth-login.js +90 -0
- package/src/auth-state.js +487 -0
- package/src/auth-store-native.js +20 -0
- package/src/auth-store-worker.js +64 -0
- package/src/auth-store.js +140 -0
- package/src/auto-paginate.js +272 -0
- package/src/bridge.js +309 -85
- package/src/cache-inspect.js +345 -0
- package/src/chain-ids.js +1 -2
- package/src/cli.js +779 -286
- package/src/commands/agent.js +20 -9
- package/src/commands/alerts.js +1 -1
- package/src/commands/completion.js +2 -15
- package/src/commands/mcp.js +22 -20
- package/src/commands/research.js +4 -2
- package/src/cost-cache.js +16 -2
- package/src/debug.js +348 -0
- package/src/doctor.js +22 -45
- package/src/ens.js +3 -1
- package/src/execute-guard.js +116 -0
- package/src/hl-action.js +41 -13
- package/src/limit-order.js +9 -1
- package/src/mcp-client-config.js +169 -0
- package/src/mcp-client-config.json +17 -0
- package/src/mcp-verify.js +6 -5
- package/src/perp.js +61 -9
- package/src/privy.js +12 -12
- package/src/query-options.js +38 -6
- package/src/response-meta.js +57 -2
- package/src/rpc-urls.js +9 -11
- package/src/schema.json +309 -30
- package/src/semver.js +23 -4
- package/src/swap-simulation.js +35 -30
- package/src/telemetry.js +20 -0
- package/src/trading.js +806 -40
- package/src/transfer.js +75 -9
- package/src/update-check.js +9 -1
- package/src/wallet.js +240 -20
- package/src/walletconnect-trading.js +29 -8
- package/src/walletconnect-x402.js +9 -5
- package/src/x402-svm.js +123 -64
- 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
|
-
import { readResponseMeta } from './response-meta.js';
|
|
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.
|
|
@@ -50,6 +54,8 @@ export const ErrorCode = {
|
|
|
50
54
|
UNAUTHORIZED: 'UNAUTHORIZED', // 401 - Invalid or missing API key
|
|
51
55
|
FORBIDDEN: 'FORBIDDEN', // 403 - Valid key but insufficient permissions
|
|
52
56
|
CREDITS_EXHAUSTED: 'CREDITS_EXHAUSTED', // 403 - Insufficient API credits
|
|
57
|
+
PLAN_UPGRADE_REQUIRED: 'PLAN_UPGRADE_REQUIRED', // 403 - Feature needs a higher subscription plan
|
|
58
|
+
GEO_BLOCKED: 'GEO_BLOCKED', // 451 - Not available in the caller's region
|
|
53
59
|
PAYMENT_REQUIRED: 'PAYMENT_REQUIRED', // 402 - x402 payment required
|
|
54
60
|
|
|
55
61
|
// Rate Limiting
|
|
@@ -62,11 +68,15 @@ export const ErrorCode = {
|
|
|
62
68
|
INVALID_PARAMS: 'INVALID_PARAMS', // Generic parameter validation error
|
|
63
69
|
MISSING_PARAM: 'MISSING_PARAM', // Required parameter not provided
|
|
64
70
|
UNSUPPORTED_FILTER: 'UNSUPPORTED_FILTER', // Filter not supported for this token/chain
|
|
71
|
+
QUERY_TOO_LARGE: 'QUERY_TOO_LARGE', // Query would return too much data - narrow it; retrying will not help
|
|
72
|
+
PAYLOAD_TOO_LARGE: 'PAYLOAD_TOO_LARGE', // 413 - Request body exceeds the size limit
|
|
65
73
|
|
|
66
74
|
// Resource Errors
|
|
67
75
|
NOT_FOUND: 'NOT_FOUND', // 404 - Resource not found
|
|
68
76
|
TOKEN_NOT_FOUND: 'TOKEN_NOT_FOUND', // Token doesn't exist
|
|
69
77
|
ADDRESS_NOT_FOUND: 'ADDRESS_NOT_FOUND', // Address has no data
|
|
78
|
+
METHOD_NOT_ALLOWED: 'METHOD_NOT_ALLOWED', // 405 - HTTP method not allowed for this endpoint
|
|
79
|
+
CONFLICT: 'CONFLICT', // 409 - Request conflicts with the current state
|
|
70
80
|
|
|
71
81
|
// Server Errors
|
|
72
82
|
SERVER_ERROR: 'SERVER_ERROR', // 500+ - Nansen API internal error
|
|
@@ -96,8 +106,8 @@ export const ErrorCode = {
|
|
|
96
106
|
* parse (e.g. PASSWORD_REQUIRED, API_KEY_REQUIRED).
|
|
97
107
|
*/
|
|
98
108
|
export class CommandError extends Error {
|
|
99
|
-
constructor(message, code = 'COMMAND_ERROR', data = null) {
|
|
100
|
-
super(message);
|
|
109
|
+
constructor(message, code = 'COMMAND_ERROR', data = null, options = undefined) {
|
|
110
|
+
super(message, options); // options.cause keeps the originating error attached
|
|
101
111
|
this.name = 'CommandError';
|
|
102
112
|
this.code = code;
|
|
103
113
|
this.data = data;
|
|
@@ -127,21 +137,70 @@ export class NansenError extends Error {
|
|
|
127
137
|
}
|
|
128
138
|
|
|
129
139
|
/**
|
|
130
|
-
* Stable snake_case codes the
|
|
140
|
+
* Stable snake_case codes the API sends in error bodies, mapped to the
|
|
131
141
|
* ErrorCode values downstream consumers already key on.
|
|
142
|
+
*
|
|
143
|
+
* Every code documented at
|
|
144
|
+
* https://docs.nansen.ai/getting-started/error-handling has an entry here, so
|
|
145
|
+
* friendly messages and agent-facing hints engage for each of them. A code
|
|
146
|
+
* missing from this map passes through statusToErrorCode verbatim; keep the
|
|
147
|
+
* table in step with that page when the API adds a code.
|
|
132
148
|
*/
|
|
133
|
-
const SERVER_CODE_MAP = {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
149
|
+
export const SERVER_CODE_MAP = {
|
|
150
|
+
// Request validation (400 / 422)
|
|
151
|
+
missing_field: ErrorCode.MISSING_PARAM,
|
|
152
|
+
unknown_field: ErrorCode.INVALID_PARAMS,
|
|
153
|
+
invalid_field_value: ErrorCode.INVALID_PARAMS,
|
|
154
|
+
invalid_address_format: ErrorCode.INVALID_ADDRESS,
|
|
155
|
+
invalid_date_format: ErrorCode.INVALID_PARAMS,
|
|
156
|
+
invalid_date_range: ErrorCode.INVALID_PARAMS,
|
|
157
|
+
mutually_exclusive_fields: ErrorCode.INVALID_PARAMS,
|
|
158
|
+
value_out_of_range: ErrorCode.INVALID_PARAMS,
|
|
159
|
+
too_many_items: ErrorCode.INVALID_PARAMS,
|
|
160
|
+
// Authentication, authorization, quota
|
|
161
|
+
unauthenticated: ErrorCode.UNAUTHORIZED,
|
|
138
162
|
forbidden: ErrorCode.FORBIDDEN,
|
|
163
|
+
geo_blocked: ErrorCode.GEO_BLOCKED,
|
|
164
|
+
plan_upgrade_required: ErrorCode.PLAN_UPGRADE_REQUIRED,
|
|
165
|
+
insufficient_credits: ErrorCode.CREDITS_EXHAUSTED,
|
|
166
|
+
rate_limit_exceeded: ErrorCode.RATE_LIMITED,
|
|
167
|
+
// Resource and request shape
|
|
139
168
|
not_found: ErrorCode.NOT_FOUND,
|
|
169
|
+
method_not_allowed: ErrorCode.METHOD_NOT_ALLOWED,
|
|
170
|
+
conflict: ErrorCode.CONFLICT,
|
|
171
|
+
payload_too_large: ErrorCode.PAYLOAD_TOO_LARGE,
|
|
172
|
+
// Server side
|
|
173
|
+
query_timeout: ErrorCode.TIMEOUT,
|
|
174
|
+
query_too_large: ErrorCode.QUERY_TOO_LARGE,
|
|
175
|
+
upstream_unavailable: ErrorCode.SERVICE_UNAVAILABLE,
|
|
176
|
+
internal_error: ErrorCode.SERVER_ERROR,
|
|
177
|
+
// Aliases from earlier error-body shapes, kept so older responses still map.
|
|
178
|
+
unauthorized: ErrorCode.UNAUTHORIZED,
|
|
179
|
+
payment_required: ErrorCode.PAYMENT_REQUIRED,
|
|
140
180
|
unsupported_filter: ErrorCode.UNSUPPORTED_FILTER,
|
|
141
181
|
validation_error: ErrorCode.INVALID_PARAMS,
|
|
142
182
|
invalid_params: ErrorCode.INVALID_PARAMS,
|
|
143
183
|
};
|
|
144
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
|
+
|
|
145
204
|
/**
|
|
146
205
|
* Map an error response to an error code.
|
|
147
206
|
*
|
|
@@ -183,8 +242,18 @@ export function statusToErrorCode(status, data = {}) {
|
|
|
183
242
|
if (messageLower.includes('token')) return ErrorCode.TOKEN_NOT_FOUND;
|
|
184
243
|
if (messageLower.includes('address') || messageLower.includes('wallet')) return ErrorCode.ADDRESS_NOT_FOUND;
|
|
185
244
|
return ErrorCode.NOT_FOUND;
|
|
245
|
+
case 405:
|
|
246
|
+
return ErrorCode.METHOD_NOT_ALLOWED;
|
|
247
|
+
case 408:
|
|
248
|
+
return ErrorCode.TIMEOUT;
|
|
249
|
+
case 409:
|
|
250
|
+
return ErrorCode.CONFLICT;
|
|
251
|
+
case 413:
|
|
252
|
+
return ErrorCode.PAYLOAD_TOO_LARGE;
|
|
186
253
|
case 429:
|
|
187
254
|
return ErrorCode.RATE_LIMITED;
|
|
255
|
+
case 451:
|
|
256
|
+
return ErrorCode.GEO_BLOCKED;
|
|
188
257
|
case 500:
|
|
189
258
|
case 502:
|
|
190
259
|
return ErrorCode.SERVER_ERROR;
|
|
@@ -218,31 +287,11 @@ export function getConfigFile() {
|
|
|
218
287
|
return CONFIG_FILE;
|
|
219
288
|
}
|
|
220
289
|
|
|
221
|
-
/**
|
|
222
|
-
* Save config to ~/.nansen/config.json
|
|
223
|
-
*/
|
|
224
|
-
export function saveConfig(config) {
|
|
225
|
-
if (!fs.existsSync(CONFIG_DIR)) {
|
|
226
|
-
fs.mkdirSync(CONFIG_DIR, { mode: 0o700, recursive: true });
|
|
227
|
-
}
|
|
228
|
-
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), { mode: 0o600 });
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
/**
|
|
232
|
-
* Delete config file (logout)
|
|
233
|
-
*/
|
|
234
|
-
export function deleteConfig() {
|
|
235
|
-
if (fs.existsSync(CONFIG_FILE)) {
|
|
236
|
-
fs.unlinkSync(CONFIG_FILE);
|
|
237
|
-
return true;
|
|
238
|
-
}
|
|
239
|
-
return false;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
290
|
// ============= Response Cache =============
|
|
243
291
|
|
|
244
292
|
const CACHE_DIR = path.join(CONFIG_DIR, 'cache');
|
|
245
|
-
|
|
293
|
+
// Exported so the cache inspector reports the same default TTL the client applies.
|
|
294
|
+
export const DEFAULT_CACHE_TTL = 300; // 5 minutes
|
|
246
295
|
|
|
247
296
|
import crypto from 'crypto';
|
|
248
297
|
|
|
@@ -303,8 +352,8 @@ export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL
|
|
|
303
352
|
const cached = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
|
|
304
353
|
const age = (Date.now() - cached.timestamp) / 1000;
|
|
305
354
|
|
|
306
|
-
if (ttlSeconds <= 0 || age > ttlSeconds) {
|
|
307
|
-
//
|
|
355
|
+
if (!Number.isFinite(cached.timestamp) || ttlSeconds <= 0 || age > ttlSeconds) {
|
|
356
|
+
// Delete entries with invalid timestamps, expired entries, or disabled entries.
|
|
308
357
|
fs.unlinkSync(cacheFile);
|
|
309
358
|
return null;
|
|
310
359
|
}
|
|
@@ -397,9 +446,8 @@ export const COUNTERPARTIES_BATCH_MAX_DAYS = 90;
|
|
|
397
446
|
* validates `chain` against. Anything outside it is a 422.
|
|
398
447
|
*
|
|
399
448
|
* Deliberately NOT derived from EVM_CHAINS. That list is this CLI's own
|
|
400
|
-
* address-format/ENS set and
|
|
401
|
-
*
|
|
402
|
-
* non-EVM chain the endpoint does serve (bitcoin, tron, sui, ton, near, ...).
|
|
449
|
+
* address-format/ENS set and omits every non-EVM chain the endpoint does serve
|
|
450
|
+
* (bitcoin, tron, sui, ton, near, ...).
|
|
403
451
|
* Mirrors ADDRESS_COUNTERPARTIES_BATCH_CHAINS on the MCP side (nansen-ra#3550),
|
|
404
452
|
* which additionally drops `arc` and `starknet`; the spec enum is the contract
|
|
405
453
|
* here, so they stay in.
|
|
@@ -542,53 +590,45 @@ function classifyAutoDetectedAddress(address) {
|
|
|
542
590
|
}
|
|
543
591
|
|
|
544
592
|
export function loadConfig() {
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
// ~/.nansen/config.json (from `nansen login`)
|
|
549
|
-
if (fs.existsSync(CONFIG_FILE)) {
|
|
550
|
-
try { config = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8')); } catch (_e) { /* ignore */ }
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
// Local config.json (for development)
|
|
554
|
-
if (!config) {
|
|
555
|
-
const localConfig = path.join(__dirname, '..', 'config.json');
|
|
556
|
-
if (fs.existsSync(localConfig)) {
|
|
557
|
-
config = JSON.parse(fs.readFileSync(localConfig, 'utf8'));
|
|
558
|
-
}
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
if (!config) {
|
|
562
|
-
config = { apiKey: null, baseUrl: 'https://api.nansen.ai' };
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
// Ensure baseUrl default (config file from older versions may omit it)
|
|
566
|
-
if (!config.baseUrl) {
|
|
567
|
-
config.baseUrl = 'https://api.nansen.ai';
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
// Env vars override individual fields
|
|
571
|
-
if (process.env.NANSEN_API_KEY) {
|
|
572
|
-
config.apiKey = process.env.NANSEN_API_KEY;
|
|
573
|
-
}
|
|
574
|
-
if (process.env.NANSEN_BASE_URL) {
|
|
575
|
-
config.baseUrl = process.env.NANSEN_BASE_URL;
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
return config;
|
|
593
|
+
const view = authConfigView();
|
|
594
|
+
return { ...view.config, apiKey: view.apiKey, baseUrl: view.baseUrl };
|
|
579
595
|
}
|
|
580
596
|
|
|
581
|
-
const config = loadConfig();
|
|
582
|
-
|
|
583
597
|
// ============= Retry Configuration =============
|
|
584
598
|
|
|
585
599
|
const DEFAULT_RETRY_OPTIONS = {
|
|
586
600
|
maxRetries: 3,
|
|
587
601
|
baseDelayMs: 1000,
|
|
588
602
|
maxDelayMs: 30000,
|
|
603
|
+
// Longest server Retry-After we are willing to wait out. A longer one is not
|
|
604
|
+
// retried at all: retrying earlier than the server asked only burns the
|
|
605
|
+
// remaining attempts on more 429s.
|
|
606
|
+
maxRetryAfterMs: 120000,
|
|
589
607
|
retryOnStatus: [429, 500, 502, 503, 504],
|
|
590
608
|
};
|
|
591
609
|
|
|
610
|
+
/**
|
|
611
|
+
* Read a response body once. A fetch body can only be consumed once, and
|
|
612
|
+
* response.json() consumes it even when parsing fails, so a body the server
|
|
613
|
+
* declares as non-JSON (gateway HTML, plain text) is read as text first. It
|
|
614
|
+
* is still parsed as JSON when it turns out to be JSON; otherwise the thrown
|
|
615
|
+
* error carries the text so the caller can report it.
|
|
616
|
+
*/
|
|
617
|
+
async function readBody(response) {
|
|
618
|
+
const contentType = stringHeader(response, 'content-type');
|
|
619
|
+
if (contentType && !/json/i.test(contentType)) {
|
|
620
|
+
const rawBody = await response.text();
|
|
621
|
+
try {
|
|
622
|
+
return JSON.parse(rawBody);
|
|
623
|
+
} catch (_err) {
|
|
624
|
+
const error = new Error('Response body is not JSON');
|
|
625
|
+
error.rawBody = rawBody;
|
|
626
|
+
throw error;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
return response.json();
|
|
630
|
+
}
|
|
631
|
+
|
|
592
632
|
/**
|
|
593
633
|
* Sleep for a given number of milliseconds
|
|
594
634
|
*/
|
|
@@ -600,10 +640,12 @@ export function sleep(ms) {
|
|
|
600
640
|
* Calculate delay with exponential backoff and jitter
|
|
601
641
|
*/
|
|
602
642
|
function calculateBackoff(attempt, baseDelayMs, maxDelayMs, retryAfterMs = null) {
|
|
603
|
-
// If server specifies retry-after,
|
|
604
|
-
|
|
643
|
+
// If server specifies retry-after, wait at least that long (plus some jitter).
|
|
644
|
+
// maxDelayMs only bounds the local exponential backoff; the caller decides
|
|
645
|
+
// whether a Retry-After is too long to wait for at all.
|
|
646
|
+
if (retryAfterMs !== null && retryAfterMs !== undefined) {
|
|
605
647
|
const jitter = Math.random() * 1000;
|
|
606
|
-
return
|
|
648
|
+
return retryAfterMs + jitter;
|
|
607
649
|
}
|
|
608
650
|
|
|
609
651
|
// Exponential backoff: base * 2^attempt + random jitter
|
|
@@ -633,6 +675,20 @@ function parseRetryAfter(headerValue) {
|
|
|
633
675
|
return null;
|
|
634
676
|
}
|
|
635
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
|
+
|
|
636
692
|
/**
|
|
637
693
|
* Build a date range from today back N days
|
|
638
694
|
* @param {number} days - Number of days back from today
|
|
@@ -645,9 +701,14 @@ export function buildDateRange(days) {
|
|
|
645
701
|
}
|
|
646
702
|
|
|
647
703
|
export class NansenAPI {
|
|
648
|
-
constructor(apiKey =
|
|
649
|
-
|
|
650
|
-
this.
|
|
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;
|
|
651
712
|
this.retryOptions = { ...DEFAULT_RETRY_OPTIONS, ...options.retry };
|
|
652
713
|
this.cacheOptions = {
|
|
653
714
|
enabled: options.cache?.enabled ?? false,
|
|
@@ -663,6 +724,16 @@ export class NansenAPI {
|
|
|
663
724
|
* low-credit warning wants.
|
|
664
725
|
*/
|
|
665
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;
|
|
666
737
|
/** API path of the most recent request(), for pairing lastResponseMeta with a cost estimate. */
|
|
667
738
|
this.lastEndpoint = null;
|
|
668
739
|
/**
|
|
@@ -678,6 +749,19 @@ export class NansenAPI {
|
|
|
678
749
|
this.servedFromCache = false;
|
|
679
750
|
}
|
|
680
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
|
+
|
|
681
765
|
static cleanBody(body) {
|
|
682
766
|
return Object.fromEntries(
|
|
683
767
|
Object.entries(body).filter(([_, v]) =>
|
|
@@ -693,7 +777,7 @@ export class NansenAPI {
|
|
|
693
777
|
* sentinel if the server cleanly, legibly rejected it without settling.
|
|
694
778
|
* Throws a NansenError(PAYMENT_AMBIGUOUS) — instead of returning the sentinel —
|
|
695
779
|
* for any outcome that doesn't prove the payment was rejected: a transport
|
|
696
|
-
* 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
|
|
697
781
|
* parsed. In all of those cases the server may already have received and
|
|
698
782
|
* settled the payment, so the caller must not treat it as safe to retry with
|
|
699
783
|
* a different option — that would risk paying twice for the same request.
|
|
@@ -717,6 +801,12 @@ export class NansenAPI {
|
|
|
717
801
|
const method = options.method || 'POST';
|
|
718
802
|
const isGet = method === 'GET';
|
|
719
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' });
|
|
720
810
|
try {
|
|
721
811
|
paidResponse = await fetch(url, {
|
|
722
812
|
method,
|
|
@@ -733,6 +823,7 @@ export class NansenAPI {
|
|
|
733
823
|
...(!isGet && method !== 'DELETE' && { body: JSON.stringify(NansenAPI.cleanBody(body)) }),
|
|
734
824
|
});
|
|
735
825
|
} catch (err) {
|
|
826
|
+
traceError({ method, url, durationMs: Date.now() - startedAt, attempt: 1, error: err.message });
|
|
736
827
|
// The signature was already on the wire when the connection failed —
|
|
737
828
|
// the server may have received and settled it before we lost the
|
|
738
829
|
// response. Fail closed rather than let the caller sign and send a
|
|
@@ -742,7 +833,26 @@ export class NansenAPI {
|
|
|
742
833
|
ErrorCode.PAYMENT_AMBIGUOUS,
|
|
743
834
|
);
|
|
744
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
|
+
});
|
|
745
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
|
+
}
|
|
746
856
|
// A 5xx doesn't prove the payment was rejected — the server could have
|
|
747
857
|
// processed it before failing to respond. Only a readable non-5xx
|
|
748
858
|
// rejection body is safe to treat as "try the next option".
|
|
@@ -794,8 +904,15 @@ export class NansenAPI {
|
|
|
794
904
|
|
|
795
905
|
async request(endpoint, body = {}, options = {}) {
|
|
796
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()));
|
|
797
914
|
const url = `${this.baseUrl}${endpoint}`;
|
|
798
|
-
const { maxRetries, baseDelayMs, maxDelayMs, retryOnStatus } = this.retryOptions;
|
|
915
|
+
const { maxRetries, baseDelayMs, maxDelayMs, maxRetryAfterMs, retryOnStatus } = this.retryOptions;
|
|
799
916
|
const shouldRetry = options.retry !== false; // Allow disabling retry per-request
|
|
800
917
|
|
|
801
918
|
// Check cache first (if enabled and not bypassed)
|
|
@@ -806,18 +923,20 @@ export class NansenAPI {
|
|
|
806
923
|
// cacheContext is therefore null unless caching is on; the `&& cacheContext`
|
|
807
924
|
// guards below ensure that null never reaches getCacheKey, where a missing
|
|
808
925
|
// identity would silently produce a credential-agnostic (shared) cache key.
|
|
809
|
-
const
|
|
926
|
+
const credentialContext = () => useCache
|
|
810
927
|
? {
|
|
811
|
-
baseUrl: this.baseUrl
|
|
928
|
+
baseUrl: `${this.baseUrl}#${this.selection.generation || ""}`,
|
|
812
929
|
method,
|
|
813
|
-
identity: computeIdentityDigest(this.apiKey, this.defaultHeaders, options.headers),
|
|
930
|
+
identity: computeIdentityDigest(this.apiKey, credentialHeaders, this.defaultHeaders, options.headers),
|
|
814
931
|
}
|
|
815
932
|
: null;
|
|
816
933
|
|
|
934
|
+
let cacheContext = credentialContext();
|
|
817
935
|
if (useCache && cacheContext) {
|
|
818
936
|
const cached = getCachedResponse(endpoint, body, cacheTtl, cacheContext);
|
|
819
937
|
if (cached) {
|
|
820
938
|
this.servedFromCache = true;
|
|
939
|
+
traceCacheHit({ method, url });
|
|
821
940
|
return cached;
|
|
822
941
|
}
|
|
823
942
|
}
|
|
@@ -825,8 +944,20 @@ export class NansenAPI {
|
|
|
825
944
|
|
|
826
945
|
let lastError;
|
|
827
946
|
|
|
828
|
-
|
|
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
|
+
}
|
|
829
958
|
let response;
|
|
959
|
+
const startedAt = Date.now();
|
|
960
|
+
traceRequest({ method, url, attempt: attempt + 1, maxAttempts });
|
|
830
961
|
try {
|
|
831
962
|
const isGet = method === 'GET';
|
|
832
963
|
response = await fetch(url, {
|
|
@@ -837,7 +968,7 @@ export class NansenAPI {
|
|
|
837
968
|
'X-Client-Type': 'nansen-cli',
|
|
838
969
|
'X-Client-Version': packageVersion,
|
|
839
970
|
...telemetryHeaders(),
|
|
840
|
-
...
|
|
971
|
+
...credentialHeaders,
|
|
841
972
|
...this.defaultHeaders,
|
|
842
973
|
...options.headers
|
|
843
974
|
},
|
|
@@ -845,41 +976,62 @@ export class NansenAPI {
|
|
|
845
976
|
});
|
|
846
977
|
} catch (err) {
|
|
847
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 });
|
|
848
980
|
lastError = new NansenError(
|
|
849
|
-
`Network error: ${err.message}`,
|
|
981
|
+
this.selection.kind === 'session' ? 'API request failed. Check your connection and retry.' : `Network error: ${err.message}`,
|
|
850
982
|
ErrorCode.NETWORK_ERROR,
|
|
851
983
|
null,
|
|
852
|
-
{ originalError: err.message, attempt: attempt + 1 }
|
|
984
|
+
{ ...(this.selection.kind !== 'session' && { originalError: err.message }), attempt: attempt + 1 }
|
|
853
985
|
);
|
|
854
|
-
|
|
986
|
+
|
|
855
987
|
if (shouldRetry && attempt < maxRetries) {
|
|
856
988
|
const delayMs = calculateBackoff(attempt, baseDelayMs, maxDelayMs);
|
|
989
|
+
traceRetry({ method, url, attempt: attempt + 1, reason: 'network-error', delayMs });
|
|
857
990
|
await sleep(delayMs);
|
|
858
991
|
continue;
|
|
859
992
|
}
|
|
860
993
|
throw lastError;
|
|
861
994
|
}
|
|
862
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
|
+
|
|
863
1007
|
let data;
|
|
864
1008
|
try {
|
|
865
|
-
data = await response
|
|
866
|
-
} catch (
|
|
1009
|
+
data = await readBody(response);
|
|
1010
|
+
} catch (err) {
|
|
867
1011
|
// Non-JSON response (rare, usually server errors)
|
|
868
|
-
const meta = readResponseMeta(response);
|
|
1012
|
+
const meta = this.selection.kind === 'session' ? browserSessionResponseMeta(response) : readResponseMeta(response);
|
|
869
1013
|
this.lastResponseMeta = meta;
|
|
1014
|
+
// readBody already holds the text when the server declared a non-JSON
|
|
1015
|
+
// body; otherwise try to read it now (null once json() consumed it).
|
|
1016
|
+
const rawBody = err?.rawBody ?? await response.text().catch(() => null);
|
|
1017
|
+
const retryAfterMs = parseRetryAfter(stringHeader(response, 'retry-after'));
|
|
870
1018
|
const error = new NansenError(
|
|
871
1019
|
`Invalid response from API (status ${response.status})`,
|
|
872
|
-
response.status
|
|
1020
|
+
statusToErrorCode(response.status, {}),
|
|
873
1021
|
response.status,
|
|
874
1022
|
{
|
|
875
|
-
body:
|
|
1023
|
+
...(this.selection.kind !== 'session' && { body: rawBody }),
|
|
876
1024
|
attempt: attempt + 1,
|
|
1025
|
+
retryAfterMs,
|
|
877
1026
|
...(meta?.requestId && { requestId: meta.requestId })
|
|
878
1027
|
}
|
|
879
1028
|
);
|
|
880
1029
|
|
|
881
|
-
|
|
882
|
-
|
|
1030
|
+
// Same retry policy as a JSON error body: a rate limiter or gateway
|
|
1031
|
+
// that answers in plain text or HTML is still a 429/5xx.
|
|
1032
|
+
if (shouldRetry && attempt < maxRetries && retryOnStatus.includes(response.status)) {
|
|
1033
|
+
const delayMs = calculateBackoff(attempt, baseDelayMs, maxDelayMs, retryAfterMs);
|
|
1034
|
+
traceRetry({ method, url, status: response.status, attempt: attempt + 1, reason: 'unparseable-response', delayMs, retryAfterMs });
|
|
883
1035
|
await sleep(delayMs);
|
|
884
1036
|
lastError = error;
|
|
885
1037
|
continue;
|
|
@@ -897,21 +1049,43 @@ export class NansenAPI {
|
|
|
897
1049
|
// an apostrophe inside the message (e.g. "can't") doesn't truncate it.
|
|
898
1050
|
const nestedMatch = typeof message === 'string' && message.match(/['"]message['"]\s*:\s*['"](.*?)['"]\s*[,}]/s);
|
|
899
1051
|
if (nestedMatch) message = nestedMatch[1];
|
|
900
|
-
const
|
|
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;
|
|
901
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
|
+
}
|
|
902
1062
|
|
|
903
1063
|
// Enhance messages for specific error codes
|
|
904
1064
|
if (code === ErrorCode.UNAUTHORIZED) {
|
|
905
|
-
message = this.apiKey ? message : 'Not logged in. Run: nansen login';
|
|
1065
|
+
message = this.apiKey || safeSessionError ? message : 'Not logged in. Run: nansen login';
|
|
906
1066
|
} else if (code === ErrorCode.UNSUPPORTED_FILTER) {
|
|
907
1067
|
message = message.replace(/\.+$/, '') + '. This filter is not supported for this token/chain combination. Do not retry.';
|
|
908
1068
|
} else if (code === ErrorCode.CREDITS_EXHAUSTED) {
|
|
909
1069
|
message = message.replace(/\.+$/, '') + '. No retry will help. Check your Nansen dashboard for credit balance.';
|
|
910
|
-
} else if (code === ErrorCode.PAYMENT_REQUIRED) {
|
|
1070
|
+
} else if (code === ErrorCode.PAYMENT_REQUIRED && response.status === 402) {
|
|
911
1071
|
// Try x402 auto-payment: local wallet (with network fallback), then WalletConnect
|
|
912
|
-
const hasManualSignature =
|
|
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
|
+
}
|
|
913
1079
|
|
|
914
|
-
if (!hasManualSignature) {
|
|
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
|
+
}
|
|
1087
|
+
|
|
1088
|
+
if (mayAutoPay && !hasManualSignature) {
|
|
915
1089
|
// Determine payment method from default wallet's provider
|
|
916
1090
|
let defaultWalletProvider = 'local';
|
|
917
1091
|
let defaultWalletName = 'unknown';
|
|
@@ -924,7 +1098,7 @@ export class NansenAPI {
|
|
|
924
1098
|
defaultWalletProvider = wallet.provider || 'local';
|
|
925
1099
|
}
|
|
926
1100
|
} catch (err) {
|
|
927
|
-
|
|
1101
|
+
trace('x402.wallet_provider_lookup_failed', { error: err.message });
|
|
928
1102
|
}
|
|
929
1103
|
|
|
930
1104
|
if (defaultWalletProvider === 'privy') {
|
|
@@ -941,7 +1115,7 @@ export class NansenAPI {
|
|
|
941
1115
|
// treated as an ordinary payment failure — there is no other
|
|
942
1116
|
// provider to fall back to here, and retrying could double-pay.
|
|
943
1117
|
if (privyErr instanceof NansenError && privyErr.code === ErrorCode.PAYMENT_AMBIGUOUS) throw privyErr;
|
|
944
|
-
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}`;
|
|
945
1119
|
}
|
|
946
1120
|
} else {
|
|
947
1121
|
// Local wallet or no wallet: existing local wallet + WalletConnect flow
|
|
@@ -970,11 +1144,11 @@ export class NansenAPI {
|
|
|
970
1144
|
try {
|
|
971
1145
|
paymentRequirements = JSON.parse(Buffer.from(paymentHeader, 'base64').toString('utf8'));
|
|
972
1146
|
} catch {
|
|
973
|
-
data.paymentRequiredRaw = paymentHeader;
|
|
1147
|
+
if (!safeSessionError) data.paymentRequiredRaw = paymentHeader;
|
|
974
1148
|
}
|
|
975
1149
|
}
|
|
976
|
-
if (!paymentRequirements &&
|
|
977
|
-
paymentRequirements =
|
|
1150
|
+
if (!paymentRequirements && bodyPaymentRequirements) {
|
|
1151
|
+
paymentRequirements = bodyPaymentRequirements;
|
|
978
1152
|
}
|
|
979
1153
|
|
|
980
1154
|
if (paymentRequirements) {
|
|
@@ -989,24 +1163,19 @@ export class NansenAPI {
|
|
|
989
1163
|
// ordinary "payment failed" that invites the caller to
|
|
990
1164
|
// retry the whole request (and sign yet another payment).
|
|
991
1165
|
if (x402Err instanceof NansenError && x402Err.code === ErrorCode.PAYMENT_AMBIGUOUS) throw x402Err;
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
message = `x402 auto-payment failed: ${x402Err.message}`;
|
|
999
|
-
}
|
|
1000
|
-
}
|
|
1001
|
-
if (this.apiKey) {
|
|
1002
|
-
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)';
|
|
1003
1172
|
}
|
|
1004
1173
|
}
|
|
1005
1174
|
}
|
|
1006
1175
|
}
|
|
1007
1176
|
}
|
|
1008
1177
|
|
|
1009
|
-
if (!message || message === data.message) {
|
|
1178
|
+
if ((mayAutoPay || hasManualSignature) && (!message || message === data.message)) {
|
|
1010
1179
|
message = 'Payment required (x402). Sign the paymentRequirements below per https://docs.x402.org and pass the result with --x402-payment-signature <value>.';
|
|
1011
1180
|
}
|
|
1012
1181
|
}
|
|
@@ -1019,7 +1188,7 @@ export class NansenAPI {
|
|
|
1019
1188
|
// On a retried call this is the LAST attempt's id — each attempt gets
|
|
1020
1189
|
// its own server-side id, and the last one is the failure worth
|
|
1021
1190
|
// reporting.
|
|
1022
|
-
const meta = readResponseMeta(response);
|
|
1191
|
+
const meta = this.selection.kind === 'session' ? browserSessionResponseMeta(response) : readResponseMeta(response);
|
|
1023
1192
|
this.lastResponseMeta = meta;
|
|
1024
1193
|
lastError = new NansenError(message, code, response.status, {
|
|
1025
1194
|
...data,
|
|
@@ -1030,9 +1199,27 @@ export class NansenAPI {
|
|
|
1030
1199
|
...(meta?.rateLimit && { rateLimit: meta.rateLimit })
|
|
1031
1200
|
});
|
|
1032
1201
|
|
|
1033
|
-
// Retry on specific status codes
|
|
1034
|
-
|
|
1035
|
-
|
|
1202
|
+
// Retry on specific status codes. A 429 Retry-After is binding: retrying
|
|
1203
|
+
// earlier only burns attempts on more 429s, so wait it out in full or,
|
|
1204
|
+
// if it is longer than we are willing to block, give up right away (the
|
|
1205
|
+
// error already carries retryAfterMs so the caller can come back later).
|
|
1206
|
+
// A Retry-After on a 5xx is only advisory and keeps the old maxDelayMs cap.
|
|
1207
|
+
const isRateLimit = response.status === 429;
|
|
1208
|
+
if (shouldRetry && attempt < maxRetries && retryOnStatus.includes(response.status)
|
|
1209
|
+
&& !(isRateLimit && retryAfterMs !== null && retryAfterMs > maxRetryAfterMs)) {
|
|
1210
|
+
const serverDelayMs = retryAfterMs === null || isRateLimit
|
|
1211
|
+
? retryAfterMs
|
|
1212
|
+
: Math.min(retryAfterMs, maxDelayMs);
|
|
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
|
+
});
|
|
1036
1223
|
await sleep(delayMs);
|
|
1037
1224
|
continue;
|
|
1038
1225
|
}
|
|
@@ -1069,7 +1256,7 @@ export class NansenAPI {
|
|
|
1069
1256
|
// ============= Account Endpoint =============
|
|
1070
1257
|
|
|
1071
1258
|
async getAccount() {
|
|
1072
|
-
return this.request('/api/v1/account', {}, { method: 'GET', cache: false });
|
|
1259
|
+
return this.request('/api/v1/account', {}, { method: 'GET', cache: false, allowPayment: false });
|
|
1073
1260
|
}
|
|
1074
1261
|
|
|
1075
1262
|
// ============= Chain Endpoints =============
|
|
@@ -1171,13 +1358,13 @@ export class NansenAPI {
|
|
|
1171
1358
|
}
|
|
1172
1359
|
|
|
1173
1360
|
async addressLabels(params = {}) {
|
|
1174
|
-
const { address, chain = 'ethereum', pagination = { page: 1, per_page: 100 } } = params;
|
|
1361
|
+
const { address, chain = 'ethereum', pagination = { page: 1, per_page: 100 }, requestOptions } = params;
|
|
1175
1362
|
if (address) requireValidAddress(address, chain);
|
|
1176
1363
|
return this.request('/api/v1/profiler/address/labels', {
|
|
1177
1364
|
address,
|
|
1178
1365
|
chain,
|
|
1179
1366
|
pagination
|
|
1180
|
-
});
|
|
1367
|
+
}, requestOptions);
|
|
1181
1368
|
}
|
|
1182
1369
|
|
|
1183
1370
|
async addressPremiumLabels(params = {}) {
|
|
@@ -1205,7 +1392,7 @@ export class NansenAPI {
|
|
|
1205
1392
|
}
|
|
1206
1393
|
|
|
1207
1394
|
async addressPnl(params = {}) {
|
|
1208
|
-
const { address, chain = 'ethereum', date, days = 30, filters = {}, orderBy, pagination } = params;
|
|
1395
|
+
const { address, chain = 'ethereum', date, days = 30, filters = {}, orderBy, pagination, requestOptions } = params;
|
|
1209
1396
|
if (address) requireValidAddress(address, chain);
|
|
1210
1397
|
const dateRange = date || buildDateRange(days);
|
|
1211
1398
|
return this.request('/api/v1/profiler/address/pnl', {
|
|
@@ -1215,7 +1402,7 @@ export class NansenAPI {
|
|
|
1215
1402
|
filters,
|
|
1216
1403
|
order_by: orderBy,
|
|
1217
1404
|
pagination
|
|
1218
|
-
});
|
|
1405
|
+
}, requestOptions);
|
|
1219
1406
|
}
|
|
1220
1407
|
|
|
1221
1408
|
async entitySearch(params = {}) {
|
|
@@ -1304,7 +1491,7 @@ export class NansenAPI {
|
|
|
1304
1491
|
}
|
|
1305
1492
|
|
|
1306
1493
|
async addressCounterparties(params = {}) {
|
|
1307
|
-
const { address, chain = 'ethereum', filters = {}, orderBy, pagination, days = 30 } = params;
|
|
1494
|
+
const { address, chain = 'ethereum', filters = {}, orderBy, pagination, days = 30, requestOptions } = params;
|
|
1308
1495
|
if (address) requireValidAddress(address, chain);
|
|
1309
1496
|
return this.request('/api/v1/profiler/address/counterparties', {
|
|
1310
1497
|
address,
|
|
@@ -1313,7 +1500,7 @@ export class NansenAPI {
|
|
|
1313
1500
|
filters,
|
|
1314
1501
|
order_by: orderBy,
|
|
1315
1502
|
pagination
|
|
1316
|
-
});
|
|
1503
|
+
}, requestOptions);
|
|
1317
1504
|
}
|
|
1318
1505
|
|
|
1319
1506
|
/**
|
|
@@ -2038,7 +2225,10 @@ export class NansenAPI {
|
|
|
2038
2225
|
}
|
|
2039
2226
|
|
|
2040
2227
|
async alertsUpdate(params = {}) {
|
|
2041
|
-
|
|
2228
|
+
// Same hazard as alertsCreate: an update that sets channels makes the
|
|
2229
|
+
// server re-send the channel welcome message, so a lost response after a
|
|
2230
|
+
// committed update must not resend the PATCH through the retry loop.
|
|
2231
|
+
return this.request('/api/v1/smart-alert', params, { method: 'PATCH', cache: false, retry: false });
|
|
2042
2232
|
}
|
|
2043
2233
|
|
|
2044
2234
|
async alertsToggle(params = {}) {
|