nansen-cli 2.2.0 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +108 -0
- package/README.md +109 -33
- package/docs/auth.md +56 -0
- package/docs/browser-login.md +101 -7
- package/docs/error-codes.md +249 -0
- package/package.json +10 -4
- package/skills/nansen-agent-guide/SKILL.md +54 -1
- package/skills/nansen-alerts-webhook-listener/SKILL.md +1 -1
- package/skills/nansen-dca-tracker/SKILL.md +1 -1
- package/skills/nansen-defi-positions/SKILL.md +1 -1
- package/skills/nansen-exit-signals/SKILL.md +2 -2
- package/skills/nansen-fund-tracker/SKILL.md +1 -1
- package/skills/nansen-general-search/SKILL.md +1 -1
- package/skills/nansen-holder-analysis/SKILL.md +2 -2
- package/skills/nansen-limit-orders/SKILL.md +1 -1
- package/skills/nansen-mpp-payment/SKILL.md +2 -2
- package/skills/nansen-perp-screener/SKILL.md +1 -1
- package/skills/nansen-perp-trader-profile/SKILL.md +1 -1
- package/skills/nansen-polymarket-deep-dive/SKILL.md +1 -1
- package/skills/nansen-polymarket-insider-scan/SKILL.md +1 -1
- package/skills/nansen-polymarket-trader-profile/SKILL.md +1 -1
- package/skills/nansen-portfolio-tracker/SKILL.md +1 -1
- package/skills/nansen-prediction-markets/SKILL.md +1 -1
- package/skills/nansen-sm-cross-chain-flows/SKILL.md +1 -1
- package/skills/nansen-smart-alerts/SKILL.md +2 -1
- package/skills/nansen-smart-money-alpha/SKILL.md +1 -1
- package/skills/nansen-smart-money-tracker/SKILL.md +8 -7
- package/skills/nansen-smart-money-trend/SKILL.md +1 -1
- package/skills/nansen-token-research/SKILL.md +1 -1
- package/skills/nansen-token-screener/SKILL.md +1 -1
- package/skills/nansen-token-transfer-analysis/SKILL.md +1 -1
- package/skills/nansen-trading/SKILL.md +1 -1
- package/skills/nansen-wallet-batch/SKILL.md +1 -1
- package/skills/nansen-wallet-clustering/SKILL.md +1 -1
- package/skills/nansen-wallet-deep-dive/SKILL.md +1 -1
- package/skills/nansen-wallet-keychain-migration/SKILL.md +1 -1
- package/skills/nansen-wallet-manager/SKILL.md +1 -1
- package/skills/nansen-wallet-profiler/SKILL.md +1 -1
- package/skills/nansen-web-fetcher/SKILL.md +1 -1
- package/skills/nansen-web-searcher/SKILL.md +1 -1
- package/src/api-endpoints.json +1605 -0
- package/src/api.js +336 -121
- package/src/auth-credentials.js +1 -0
- package/src/auth-state.js +2 -2
- package/src/auth-store-native.js +6 -1
- package/src/auth-store-worker.js +1 -1
- package/src/auth-store.js +9 -4
- package/src/bridge.js +19 -10
- package/src/cli.js +258 -107
- package/src/commands/agent.js +2 -3
- package/src/commands/alerts.js +277 -9
- package/src/commands/completion.js +6 -1
- package/src/commands/feedback.js +413 -0
- package/src/commands/mcp.js +1 -1
- package/src/commands/research.js +14 -37
- package/src/cost-cache.js +33 -7
- package/src/doctor.js +14 -5
- package/src/error-codes.js +226 -0
- package/src/feedback-journal.js +86 -0
- package/src/input-validation.js +551 -0
- package/src/limit-order.js +12 -3
- package/src/perp.js +2 -1
- package/src/privy.js +144 -48
- package/src/query-options.js +30 -7
- package/src/rpc-urls.js +3 -1
- package/src/schema.json +1254 -150
- package/src/solana-tx.js +4 -0
- package/src/telemetry.js +5 -1
- package/src/trade-validation.js +190 -21
- package/src/trading.js +229 -129
- package/src/transfer.js +7 -1
- package/src/update-check.js +32 -5
- package/src/wallet.js +220 -57
- package/src/walletconnect-x402.js +152 -52
- package/src/x402-audit.js +191 -0
- package/src/x402-payment-balance.js +90 -0
- package/src/x402-policy.js +151 -4
- package/src/x402.js +51 -22
package/src/api.js
CHANGED
|
@@ -13,6 +13,8 @@ import { EVM_CHAINS } from './chain-ids.js';
|
|
|
13
13
|
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
|
+
import { appendPaymentRecord, newPaymentId, sanitizeRequestUrl } from './x402-audit.js';
|
|
17
|
+
import { openLocalFile } from './local-file.js';
|
|
16
18
|
|
|
17
19
|
/**
|
|
18
20
|
* Key for the credit/rate-limit metadata attached to a successful response.
|
|
@@ -33,6 +35,41 @@ export const RESPONSE_META = Symbol('nansenResponseMeta');
|
|
|
33
35
|
*/
|
|
34
36
|
export const X402_PAYMENT_REJECTED = Symbol('x402PaymentRejected');
|
|
35
37
|
|
|
38
|
+
/**
|
|
39
|
+
* True when an x402 rejection body carries a reason code for an underfunded
|
|
40
|
+
* payer, e.g. "insufficient_funds" or "invalid_exact_evm_insufficient_balance".
|
|
41
|
+
* Only the machine-readable reason fields are read, so free text elsewhere in
|
|
42
|
+
* the body (such as an accepts[].description) can't trigger it.
|
|
43
|
+
*/
|
|
44
|
+
function isInsufficientBalanceRejection(data) {
|
|
45
|
+
if (data === null || typeof data !== 'object') return false;
|
|
46
|
+
return [data.error, data.invalidReason].some(
|
|
47
|
+
reason => typeof reason === 'string' && /insufficient_(funds|balance)\b/i.test(reason),
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// A reason code in one letter case: "expired", "invalid_exact_evm_payload_signature",
|
|
52
|
+
// "INVALID_SIGNATURE". Hex and base58 identifiers mix digits and letters in
|
|
53
|
+
// ways this can't match (a lone word has no digits; base58 mixes case), so
|
|
54
|
+
// addresses and account keys are never copied.
|
|
55
|
+
const REASON_CODE = /^(?:[a-z]+(?:_[a-z0-9]+)*|[A-Z]+(?:_[A-Z0-9]+)*)$/;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The rejection's reason for the audit log, or null. Only a code matching
|
|
59
|
+
* REASON_CODE is copied, never free text. A non-402 status without a code is
|
|
60
|
+
* marked "unexpected_status": the retry still treats it as a rejection, but
|
|
61
|
+
* it is not a payment refusal.
|
|
62
|
+
*/
|
|
63
|
+
function rejectionReasonCode(data, status) {
|
|
64
|
+
if (isInsufficientBalanceRejection(data)) return 'insufficient_balance';
|
|
65
|
+
const code = data !== null && typeof data === 'object'
|
|
66
|
+
? [data.invalidReason, data.error].find(
|
|
67
|
+
reason => typeof reason === 'string' && reason.length <= 100 && REASON_CODE.test(reason),
|
|
68
|
+
)
|
|
69
|
+
: undefined;
|
|
70
|
+
return code ?? (status === 402 ? null : 'unexpected_status');
|
|
71
|
+
}
|
|
72
|
+
|
|
36
73
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
37
74
|
|
|
38
75
|
export function telemetryHeaders() {
|
|
@@ -46,50 +83,13 @@ export const { version: packageVersion } = JSON.parse(
|
|
|
46
83
|
|
|
47
84
|
// ============= Error Codes =============
|
|
48
85
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
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
|
|
59
|
-
PAYMENT_REQUIRED: 'PAYMENT_REQUIRED', // 402 - x402 payment required
|
|
60
|
-
|
|
61
|
-
// Rate Limiting
|
|
62
|
-
RATE_LIMITED: 'RATE_LIMITED', // 429 - Too many requests
|
|
63
|
-
|
|
64
|
-
// Validation Errors
|
|
65
|
-
INVALID_ADDRESS: 'INVALID_ADDRESS', // Address format validation failed
|
|
66
|
-
INVALID_TOKEN: 'INVALID_TOKEN', // Token address validation failed
|
|
67
|
-
INVALID_CHAIN: 'INVALID_CHAIN', // Unsupported or invalid chain
|
|
68
|
-
INVALID_PARAMS: 'INVALID_PARAMS', // Generic parameter validation error
|
|
69
|
-
MISSING_PARAM: 'MISSING_PARAM', // Required parameter not provided
|
|
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
|
|
73
|
-
|
|
74
|
-
// Resource Errors
|
|
75
|
-
NOT_FOUND: 'NOT_FOUND', // 404 - Resource not found
|
|
76
|
-
TOKEN_NOT_FOUND: 'TOKEN_NOT_FOUND', // Token doesn't exist
|
|
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
|
|
80
|
-
|
|
81
|
-
// Server Errors
|
|
82
|
-
SERVER_ERROR: 'SERVER_ERROR', // 500+ - Nansen API internal error
|
|
83
|
-
SERVICE_UNAVAILABLE: 'SERVICE_UNAVAILABLE', // 503 - API temporarily down
|
|
84
|
-
|
|
85
|
-
// Client Errors
|
|
86
|
-
NETWORK_ERROR: 'NETWORK_ERROR', // Connection failed
|
|
87
|
-
TIMEOUT: 'TIMEOUT', // Request timed out
|
|
88
|
-
PAYMENT_AMBIGUOUS: 'PAYMENT_AMBIGUOUS', // x402 payment outcome unknown after transmission — do not retry with another payment
|
|
89
|
-
|
|
90
|
-
// Generic
|
|
91
|
-
UNKNOWN: 'UNKNOWN', // Unclassified error
|
|
92
|
-
};
|
|
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';
|
|
93
93
|
|
|
94
94
|
/**
|
|
95
95
|
* Error thrown by command handlers for user-facing failures (validation errors,
|
|
@@ -201,6 +201,89 @@ export function browserSessionResponseMeta(response) {
|
|
|
201
201
|
return { ...(meta?.credits && { credits: meta.credits }), ...(meta?.rateLimit && { rateLimit: meta.rateLimit }) };
|
|
202
202
|
}
|
|
203
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
|
+
|
|
204
287
|
/**
|
|
205
288
|
* Map an error response to an error code.
|
|
206
289
|
*
|
|
@@ -348,37 +431,47 @@ export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL
|
|
|
348
431
|
return null;
|
|
349
432
|
}
|
|
350
433
|
|
|
434
|
+
let fd;
|
|
435
|
+
let primaryError;
|
|
436
|
+
let result = null;
|
|
351
437
|
try {
|
|
352
|
-
|
|
438
|
+
fd = openLocalFile(cacheFile, { root: CACHE_DIR });
|
|
439
|
+
const cached = JSON.parse(fs.readFileSync(fd, 'utf8'));
|
|
353
440
|
const age = (Date.now() - cached.timestamp) / 1000;
|
|
354
441
|
|
|
355
|
-
if (
|
|
356
|
-
//
|
|
357
|
-
|
|
358
|
-
|
|
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
|
+
}
|
|
359
461
|
}
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
const meta = { ...cached.data?._meta, fromCache: true, cacheAge: Math.round(age) };
|
|
370
|
-
if (Array.isArray(cached.data)) {
|
|
371
|
-
const rows = cached.data.slice();
|
|
372
|
-
rows._meta = meta;
|
|
373
|
-
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;
|
|
374
471
|
}
|
|
375
|
-
if (cached.data === null || typeof cached.data !== 'object') return cached.data;
|
|
376
|
-
return { ...cached.data, _meta: meta };
|
|
377
|
-
} catch (_e) {
|
|
378
|
-
// Invalid cache file, delete it
|
|
379
|
-
try { fs.unlinkSync(cacheFile); } catch { /* ignore */ }
|
|
380
|
-
return null;
|
|
381
472
|
}
|
|
473
|
+
if (!primaryError && closeError) throw closeError;
|
|
474
|
+
return result;
|
|
382
475
|
}
|
|
383
476
|
|
|
384
477
|
/**
|
|
@@ -398,7 +491,37 @@ export function setCachedResponse(endpoint, body, data, context = {}) {
|
|
|
398
491
|
data
|
|
399
492
|
};
|
|
400
493
|
|
|
401
|
-
|
|
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;
|
|
402
525
|
}
|
|
403
526
|
|
|
404
527
|
/**
|
|
@@ -508,6 +631,9 @@ function resolveCounterpartiesBatchChain(chain) {
|
|
|
508
631
|
return resolved;
|
|
509
632
|
}
|
|
510
633
|
|
|
634
|
+
/** The address the API uses for native BTC on token endpoints that accept bitcoin. */
|
|
635
|
+
export const BITCOIN_NATIVE_ADDRESS = '1111111111111111111114oLvT2';
|
|
636
|
+
|
|
511
637
|
/**
|
|
512
638
|
* Validate address format for a given chain
|
|
513
639
|
* @param {string} address - The address to validate
|
|
@@ -531,7 +657,7 @@ export function validateAddress(address, chain = 'ethereum') {
|
|
|
531
657
|
}
|
|
532
658
|
} else if (chain === 'bitcoin') {
|
|
533
659
|
if (!ADDRESS_PATTERNS.bitcoin.test(trimmed)) {
|
|
534
|
-
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 };
|
|
535
661
|
}
|
|
536
662
|
}
|
|
537
663
|
// For unknown chains, allow any non-empty string (API will validate)
|
|
@@ -734,7 +860,11 @@ export class NansenAPI {
|
|
|
734
860
|
this.paginatedResponseMeta = null;
|
|
735
861
|
/** API path paired with paginatedResponseMeta for fallback cost estimates. */
|
|
736
862
|
this.paginatedEndpoint = null;
|
|
737
|
-
/**
|
|
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
|
+
*/
|
|
738
868
|
this.lastEndpoint = null;
|
|
739
869
|
/**
|
|
740
870
|
* Whether the most recent request() was answered from the local response
|
|
@@ -781,27 +911,55 @@ export class NansenAPI {
|
|
|
781
911
|
* parsed. In all of those cases the server may already have received and
|
|
782
912
|
* settled the payment, so the caller must not treat it as safe to retry with
|
|
783
913
|
* a different option — that would risk paying twice for the same request.
|
|
784
|
-
* Logs the payment and warns about low balance
|
|
914
|
+
* Logs the payment when walletLabel is given, and warns about low balance
|
|
915
|
+
* when network is given and checkBalance is true. A rejection whose reason
|
|
916
|
+
* code says the payer is underfunded is reported on stderr before the
|
|
917
|
+
* sentinel is returned.
|
|
785
918
|
*
|
|
786
919
|
* @param {string} signature - Payment-Signature header value
|
|
787
920
|
* @param {string|null} walletLabel - Display label for logging, e.g. "local wallet alice"
|
|
788
|
-
* @param {string|null} network - x402 network string
|
|
921
|
+
* @param {string|null} network - x402 network string the payment was signed for, e.g. "eip155:8453"
|
|
789
922
|
* @param {string} url - Request URL
|
|
790
923
|
* @param {object} body - Request body (will be cleaned)
|
|
791
924
|
* @param {object} [options={}] - Request options (may include .method, .headers)
|
|
925
|
+
* @param {object} [payment={}]
|
|
926
|
+
* @param {string|null} [payment.asset=null] - Token the payment used, for the balance check
|
|
927
|
+
* @param {boolean} [payment.checkBalance=true] - Whether the local default wallet's
|
|
928
|
+
* balance reflects this payment. False for WalletConnect, which pays from an
|
|
929
|
+
* external account the low-balance warning cannot read.
|
|
930
|
+
* @param {string|null} [payment.provider=null] - "local", "privy" or "walletconnect", for the audit log
|
|
931
|
+
* @param {object|null} [payment.decision=null] - The policy decision that approved
|
|
932
|
+
* the payment ({ usd, symbol, payTo, amountRaw }), for the audit log
|
|
792
933
|
* @returns {Promise<object|typeof X402_PAYMENT_REJECTED>}
|
|
793
934
|
*
|
|
794
935
|
* TODO: full fix — extract the entire x402 provider dispatch from request() into
|
|
795
936
|
* an attemptX402Payment() method so adding a new payment provider only requires
|
|
796
937
|
* touching that one method, not hunting inside the retry loop.
|
|
797
938
|
*/
|
|
798
|
-
async _x402Retry(signature, walletLabel, network, url, body, options = {}, asset = null) {
|
|
939
|
+
async _x402Retry(signature, walletLabel, network, url, body, options = {}, { asset = null, checkBalance = true, provider = null, decision = null } = {}) {
|
|
799
940
|
// Mirror request(): paid retries must use the original method. Hardcoding
|
|
800
941
|
// POST burned a payment signature then hit the wrong route for GET/DELETE/PATCH.
|
|
801
942
|
const method = options.method || 'POST';
|
|
802
943
|
const isGet = method === 'GET';
|
|
803
944
|
let paidResponse;
|
|
804
945
|
const startedAt = Date.now();
|
|
946
|
+
// One "signed" record now and one outcome record before every exit below,
|
|
947
|
+
// sharing an id. Never the signature, bodies or query string.
|
|
948
|
+
const auditBase = {
|
|
949
|
+
id: newPaymentId(),
|
|
950
|
+
provider,
|
|
951
|
+
wallet: walletLabel,
|
|
952
|
+
network,
|
|
953
|
+
asset: decision?.asset ?? null,
|
|
954
|
+
symbol: decision?.symbol ?? null,
|
|
955
|
+
amountUsd: decision?.usd ?? null,
|
|
956
|
+
amountRaw: decision?.amountRaw ?? null,
|
|
957
|
+
payTo: decision?.payTo ?? null,
|
|
958
|
+
method,
|
|
959
|
+
requestUrl: sanitizeRequestUrl(url),
|
|
960
|
+
};
|
|
961
|
+
const audit = (event, fields = {}) => appendPaymentRecord({ ...auditBase, event, ...fields });
|
|
962
|
+
audit('signed');
|
|
805
963
|
// The signature itself is never traced — only that a paid retry went out.
|
|
806
964
|
// As in the legacy key flow, payment authenticates this retry on its own.
|
|
807
965
|
// Do not attach requestCredentials(): Bearer plus payment is rejected by API
|
|
@@ -824,6 +982,7 @@ export class NansenAPI {
|
|
|
824
982
|
});
|
|
825
983
|
} catch (err) {
|
|
826
984
|
traceError({ method, url, durationMs: Date.now() - startedAt, attempt: 1, error: err.message });
|
|
985
|
+
audit('ambiguous', { reason: 'transport_error' });
|
|
827
986
|
// The signature was already on the wire when the connection failed —
|
|
828
987
|
// the server may have received and settled it before we lost the
|
|
829
988
|
// response. Fail closed rather than let the caller sign and send a
|
|
@@ -844,10 +1003,12 @@ export class NansenAPI {
|
|
|
844
1003
|
attempt: 1,
|
|
845
1004
|
payment: 'x402',
|
|
846
1005
|
});
|
|
1006
|
+
const outcome = { httpStatus: paidResponse.status, requestId: requestIdOf(paidResponse) };
|
|
847
1007
|
if (!paidResponse.ok) {
|
|
848
1008
|
// An admission denial does not prove that a transmitted payment cannot
|
|
849
1009
|
// settle. Stop here instead of authorizing another rail or wallet.
|
|
850
1010
|
if ([401, 403, 429, 451].includes(paidResponse.status)) {
|
|
1011
|
+
audit('ambiguous', { ...outcome, reason: 'admission_denied' });
|
|
851
1012
|
throw new NansenError(
|
|
852
1013
|
`x402 payment outcome unknown: paid request was denied (${paidResponse.status}). Not attempting another payment for the same request.`,
|
|
853
1014
|
ErrorCode.PAYMENT_AMBIGUOUS,
|
|
@@ -857,25 +1018,39 @@ export class NansenAPI {
|
|
|
857
1018
|
// processed it before failing to respond. Only a readable non-5xx
|
|
858
1019
|
// rejection body is safe to treat as "try the next option".
|
|
859
1020
|
if (paidResponse.status >= 500) {
|
|
1021
|
+
audit('ambiguous', { ...outcome, reason: 'server_error' });
|
|
860
1022
|
throw new NansenError(
|
|
861
1023
|
`x402 payment outcome unknown: server returned ${paidResponse.status} after the signed payment was transmitted. Not attempting another payment for the same request.`,
|
|
862
1024
|
ErrorCode.PAYMENT_AMBIGUOUS,
|
|
863
1025
|
);
|
|
864
1026
|
}
|
|
1027
|
+
let rejection;
|
|
865
1028
|
try {
|
|
866
|
-
await paidResponse.json();
|
|
1029
|
+
rejection = await paidResponse.json();
|
|
867
1030
|
} catch (err) {
|
|
1031
|
+
audit('ambiguous', { ...outcome, reason: 'unreadable_rejection' });
|
|
868
1032
|
throw new NansenError(
|
|
869
1033
|
`x402 payment outcome unknown: rejection response body was unreadable (${err.message}). Not attempting another payment for the same request.`,
|
|
870
1034
|
ErrorCode.PAYMENT_AMBIGUOUS,
|
|
871
1035
|
);
|
|
872
1036
|
}
|
|
1037
|
+
const reason = rejectionReasonCode(rejection, paidResponse.status);
|
|
1038
|
+
if (reason === 'insufficient_balance') {
|
|
1039
|
+
console.error(
|
|
1040
|
+
`[x402] Payment rejected: ${walletLabel || 'the paying wallet'} has an insufficient token balance` +
|
|
1041
|
+
`${network ? ` on ${network}` : ''}. Fund it on that network or use another payment option.`,
|
|
1042
|
+
);
|
|
1043
|
+
}
|
|
1044
|
+
audit('rejected', { ...outcome, reason });
|
|
873
1045
|
return X402_PAYMENT_REJECTED;
|
|
874
1046
|
}
|
|
1047
|
+
// A 2xx means the payment settled: record it before the balance check and
|
|
1048
|
+
// body parse, which can be slow or interrupted.
|
|
1049
|
+
audit('accepted', outcome);
|
|
875
1050
|
if (walletLabel) {
|
|
876
1051
|
console.error(`[x402] Paid via ${walletLabel}${network ? ` (${network})` : ''}`);
|
|
877
1052
|
}
|
|
878
|
-
if (network) {
|
|
1053
|
+
if (network && checkBalance) {
|
|
879
1054
|
try {
|
|
880
1055
|
const { checkX402Balance } = await import('./x402.js');
|
|
881
1056
|
const result = await checkX402Balance(network, asset);
|
|
@@ -903,7 +1078,6 @@ export class NansenAPI {
|
|
|
903
1078
|
}
|
|
904
1079
|
|
|
905
1080
|
async request(endpoint, body = {}, options = {}) {
|
|
906
|
-
this.lastEndpoint = endpoint;
|
|
907
1081
|
const extraHeaders = { ...this.defaultHeaders, ...options.headers };
|
|
908
1082
|
let credentialHeaders = await this.requestCredentials(extraHeaders);
|
|
909
1083
|
// Keys and browser sessions share the same payment policy. Explicit raw
|
|
@@ -941,6 +1115,7 @@ export class NansenAPI {
|
|
|
941
1115
|
}
|
|
942
1116
|
}
|
|
943
1117
|
this.servedFromCache = false;
|
|
1118
|
+
this.lastEndpoint = endpoint;
|
|
944
1119
|
|
|
945
1120
|
let lastError;
|
|
946
1121
|
|
|
@@ -978,7 +1153,7 @@ export class NansenAPI {
|
|
|
978
1153
|
// Network-level errors - retry these too
|
|
979
1154
|
traceError({ method, url, durationMs: Date.now() - startedAt, attempt: attempt + 1, error: this.redactAuthDiagnostics ? 'API request failed' : err.message });
|
|
980
1155
|
lastError = new NansenError(
|
|
981
|
-
this.selection.kind === 'session'
|
|
1156
|
+
networkErrorMessage(this.baseUrl, err, { redact: this.selection.kind === 'session' }),
|
|
982
1157
|
ErrorCode.NETWORK_ERROR,
|
|
983
1158
|
null,
|
|
984
1159
|
{ ...(this.selection.kind !== 'session' && { originalError: err.message }), attempt: attempt + 1 }
|
|
@@ -1050,19 +1225,35 @@ export class NansenAPI {
|
|
|
1050
1225
|
const nestedMatch = typeof message === 'string' && message.match(/['"]message['"]\s*:\s*['"](.*?)['"]\s*[,}]/s);
|
|
1051
1226
|
if (nestedMatch) message = nestedMatch[1];
|
|
1052
1227
|
const safeSessionError = this.selection.kind === 'session' ? browserSessionError(response.status, data) : null;
|
|
1053
|
-
|
|
1228
|
+
let code = safeSessionError?.code || statusToErrorCode(response.status, data);
|
|
1054
1229
|
// Keep a body-only challenge available to the signer without exposing
|
|
1055
1230
|
// the authenticated error body through browser-session diagnostics.
|
|
1056
1231
|
const bodyPaymentRequirements = response.status === 402 ? data.paymentRequirements : undefined;
|
|
1057
1232
|
const retryAfterMs = parseRetryAfter(response.headers.get('retry-after'));
|
|
1058
1233
|
if (this.selection.kind === 'session') {
|
|
1059
|
-
|
|
1060
|
-
|
|
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);
|
|
1061
1244
|
}
|
|
1062
1245
|
|
|
1063
1246
|
// Enhance messages for specific error codes
|
|
1064
1247
|
if (code === ErrorCode.UNAUTHORIZED) {
|
|
1065
|
-
|
|
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
|
+
}
|
|
1066
1257
|
} else if (code === ErrorCode.UNSUPPORTED_FILTER) {
|
|
1067
1258
|
message = message.replace(/\.+$/, '') + '. This filter is not supported for this token/chain combination. Do not retry.';
|
|
1068
1259
|
} else if (code === ErrorCode.CREDITS_EXHAUSTED) {
|
|
@@ -1085,7 +1276,20 @@ export class NansenAPI {
|
|
|
1085
1276
|
}
|
|
1086
1277
|
}
|
|
1087
1278
|
|
|
1279
|
+
// When the session cap stopped every payment, its reason outranks
|
|
1280
|
+
// the generic payment failure below: the fix is to raise the cap, not
|
|
1281
|
+
// to change credentials. Once a payment was sent, its own outcome is
|
|
1282
|
+
// the better explanation. An invalid cap refuses every payment, so
|
|
1283
|
+
// check it once before any wallet or network work.
|
|
1284
|
+
let capRefusal = null;
|
|
1285
|
+
let paymentSent = false;
|
|
1286
|
+
const onCapRefusal = (reason) => { capRefusal = reason; };
|
|
1088
1287
|
if (mayAutoPay && !hasManualSignature) {
|
|
1288
|
+
const { sessionCapConfigError } = await import('./x402-policy.js');
|
|
1289
|
+
capRefusal = sessionCapConfigError();
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
if (mayAutoPay && !hasManualSignature && !capRefusal) {
|
|
1089
1293
|
// Determine payment method from default wallet's provider
|
|
1090
1294
|
let defaultWalletProvider = 'local';
|
|
1091
1295
|
let defaultWalletName = 'unknown';
|
|
@@ -1105,9 +1309,12 @@ export class NansenAPI {
|
|
|
1105
1309
|
// Default wallet is Privy: sign via Privy
|
|
1106
1310
|
try {
|
|
1107
1311
|
const { createPrivyPaymentSignatures } = await import('./privy.js');
|
|
1108
|
-
for await (const { signature, network } of createPrivyPaymentSignatures(response, url)) {
|
|
1109
|
-
|
|
1312
|
+
for await (const { signature, network, asset, payment, releaseCharge } of createPrivyPaymentSignatures(response, url, { onCapRefusal })) {
|
|
1313
|
+
paymentSent = true;
|
|
1314
|
+
const result = await this._x402Retry(signature, `Privy wallet ${defaultWalletName}`, network, url, body, options, { asset, provider: 'privy', decision: payment });
|
|
1110
1315
|
if (result !== X402_PAYMENT_REJECTED) return result;
|
|
1316
|
+
// A clean rejection settled nothing, so it doesn't count against the session cap.
|
|
1317
|
+
releaseCharge();
|
|
1111
1318
|
}
|
|
1112
1319
|
} catch (privyErr) {
|
|
1113
1320
|
// An ambiguous outcome (transport failure, 5xx, unreadable body)
|
|
@@ -1122,10 +1329,13 @@ export class NansenAPI {
|
|
|
1122
1329
|
// 1. Try local wallet with fallback across payment networks
|
|
1123
1330
|
try {
|
|
1124
1331
|
const { createPaymentSignatures } = await import('./x402.js');
|
|
1125
|
-
for await (const { signature, network, asset } of createPaymentSignatures(response, url)) {
|
|
1126
|
-
|
|
1332
|
+
for await (const { signature, network, asset, payment, releaseCharge } of createPaymentSignatures(response, url, { onCapRefusal })) {
|
|
1333
|
+
paymentSent = true;
|
|
1334
|
+
const result = await this._x402Retry(signature, `local wallet ${defaultWalletName}`, network, url, body, options, { asset, provider: 'local', decision: payment });
|
|
1127
1335
|
if (result !== X402_PAYMENT_REJECTED) return result;
|
|
1128
|
-
// This payment option was cleanly rejected without settling,
|
|
1336
|
+
// This payment option was cleanly rejected without settling, so it
|
|
1337
|
+
// doesn't count against the session cap. Try the next one.
|
|
1338
|
+
releaseCharge();
|
|
1129
1339
|
}
|
|
1130
1340
|
} catch (localErr) {
|
|
1131
1341
|
// An ambiguous outcome here means a signed payment may already
|
|
@@ -1153,10 +1363,18 @@ export class NansenAPI {
|
|
|
1153
1363
|
|
|
1154
1364
|
if (paymentRequirements) {
|
|
1155
1365
|
try {
|
|
1156
|
-
const {
|
|
1157
|
-
const
|
|
1158
|
-
|
|
1159
|
-
|
|
1366
|
+
const { createWalletConnectPaymentSignatures } = await import('./walletconnect-x402.js');
|
|
1367
|
+
for await (const { signature, network, payment, releaseCharge } of createWalletConnectPaymentSignatures(paymentRequirements, { onCapRefusal })) {
|
|
1368
|
+
// The network is only logged: the post-payment balance
|
|
1369
|
+
// warning reads the local default wallet, not the
|
|
1370
|
+
// WalletConnect account, so it is skipped here.
|
|
1371
|
+
paymentSent = true;
|
|
1372
|
+
const result = await this._x402Retry(signature, 'WalletConnect', network, url, body, options, { checkBalance: false, provider: 'walletconnect', decision: payment });
|
|
1373
|
+
if (result !== X402_PAYMENT_REJECTED) return result;
|
|
1374
|
+
// Cleanly rejected without settling, so it doesn't count
|
|
1375
|
+
// against the session cap. Try the next option.
|
|
1376
|
+
releaseCharge();
|
|
1377
|
+
}
|
|
1160
1378
|
} catch (x402Err) {
|
|
1161
1379
|
// WalletConnect is the last resort in this chain — an
|
|
1162
1380
|
// ambiguous outcome here still must not be reported as an
|
|
@@ -1175,6 +1393,8 @@ export class NansenAPI {
|
|
|
1175
1393
|
}
|
|
1176
1394
|
}
|
|
1177
1395
|
|
|
1396
|
+
if (capRefusal && !paymentSent) message = capRefusal;
|
|
1397
|
+
|
|
1178
1398
|
if ((mayAutoPay || hasManualSignature) && (!message || message === data.message)) {
|
|
1179
1399
|
message = 'Payment required (x402). Sign the paymentRequirements below per https://docs.x402.org and pass the result with --x402-payment-signature <value>.';
|
|
1180
1400
|
}
|
|
@@ -1191,7 +1411,7 @@ export class NansenAPI {
|
|
|
1191
1411
|
const meta = this.selection.kind === 'session' ? browserSessionResponseMeta(response) : readResponseMeta(response);
|
|
1192
1412
|
this.lastResponseMeta = meta;
|
|
1193
1413
|
lastError = new NansenError(message, code, response.status, {
|
|
1194
|
-
...data,
|
|
1414
|
+
...apiErrorDetails(data, message, response.status),
|
|
1195
1415
|
attempt: attempt + 1,
|
|
1196
1416
|
retryAfterMs,
|
|
1197
1417
|
...(meta?.requestId && { requestId: meta.requestId }),
|
|
@@ -1345,7 +1565,7 @@ export class NansenAPI {
|
|
|
1345
1565
|
// ============= Profiler Endpoints =============
|
|
1346
1566
|
|
|
1347
1567
|
async addressBalance(params = {}) {
|
|
1348
|
-
const { address, entityName, chain = 'all', hideSpamToken = true, filters = {}, orderBy } = params;
|
|
1568
|
+
const { address, entityName, chain = 'all', hideSpamToken = true, filters = {}, orderBy, pagination } = params;
|
|
1349
1569
|
if (address) requireValidAddress(address, chain);
|
|
1350
1570
|
return this.request('/api/v1/profiler/address/current-balance', {
|
|
1351
1571
|
address,
|
|
@@ -1353,7 +1573,8 @@ export class NansenAPI {
|
|
|
1353
1573
|
chain,
|
|
1354
1574
|
hide_spam_token: hideSpamToken,
|
|
1355
1575
|
filters,
|
|
1356
|
-
order_by: orderBy
|
|
1576
|
+
order_by: orderBy,
|
|
1577
|
+
pagination
|
|
1357
1578
|
});
|
|
1358
1579
|
}
|
|
1359
1580
|
|
|
@@ -1583,15 +1804,14 @@ export class NansenAPI {
|
|
|
1583
1804
|
}
|
|
1584
1805
|
|
|
1585
1806
|
async addressPnlSummary(params = {}) {
|
|
1586
|
-
// Note: pnl-summary endpoint is non-paginated (returns aggregate stats, not a list)
|
|
1587
|
-
//
|
|
1588
|
-
const { address, chain = 'ethereum',
|
|
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;
|
|
1589
1810
|
if (address) requireValidAddress(address, chain);
|
|
1590
1811
|
return this.request('/api/v1/profiler/address/pnl-summary', {
|
|
1591
1812
|
address,
|
|
1592
1813
|
chain,
|
|
1593
|
-
date: buildDateRange(days)
|
|
1594
|
-
order_by: orderBy
|
|
1814
|
+
date: buildDateRange(days)
|
|
1595
1815
|
});
|
|
1596
1816
|
}
|
|
1597
1817
|
|
|
@@ -1699,7 +1919,7 @@ export class NansenAPI {
|
|
|
1699
1919
|
// Apply smart money filter via filters object
|
|
1700
1920
|
if (onlySmartMoney) {
|
|
1701
1921
|
filters.include_smart_money_labels = filters.include_smart_money_labels ||
|
|
1702
|
-
['
|
|
1922
|
+
['Smart Trader', '30D Smart Trader', '90D Smart Trader', '180D Smart Trader'];
|
|
1703
1923
|
}
|
|
1704
1924
|
|
|
1705
1925
|
return this.request('/api/v1/tgm/dex-trades', {
|
|
@@ -1936,7 +2156,7 @@ export class NansenAPI {
|
|
|
1936
2156
|
}
|
|
1937
2157
|
|
|
1938
2158
|
async pmMarketScreener(params = {}) {
|
|
1939
|
-
const { orderBy, sortBy = 'volume_24hr', query = '', status = '', tags, minLiquidity, maxLiquidity,
|
|
2159
|
+
const { orderBy, sortBy = 'volume_24hr', query = '', status = '', tags, minLiquidity, maxLiquidity, maxUniqueTraders24h, minVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, minPrice, maxPrice, pagination } = params;
|
|
1940
2160
|
const body = {
|
|
1941
2161
|
sort_by: sortBy,
|
|
1942
2162
|
query,
|
|
@@ -1947,10 +2167,8 @@ export class NansenAPI {
|
|
|
1947
2167
|
if (tags && tags.length) body.tags = tags;
|
|
1948
2168
|
if (minLiquidity != null) body.min_liquidity = minLiquidity;
|
|
1949
2169
|
if (maxLiquidity != null) body.max_liquidity = maxLiquidity;
|
|
1950
|
-
if (minUniqueTraders24h != null) body.min_unique_traders_24h = minUniqueTraders24h;
|
|
1951
2170
|
if (maxUniqueTraders24h != null) body.max_unique_traders_24h = maxUniqueTraders24h;
|
|
1952
2171
|
if (minVolume24hr != null) body.min_volume_24hr = minVolume24hr;
|
|
1953
|
-
if (maxVolume24hr != null) body.max_volume_24hr = maxVolume24hr;
|
|
1954
2172
|
if (negRisk != null) body.neg_risk = negRisk;
|
|
1955
2173
|
if (minOpenInterest != null) body.min_open_interest = minOpenInterest;
|
|
1956
2174
|
if (maxOpenInterest != null) body.max_open_interest = maxOpenInterest;
|
|
@@ -1962,7 +2180,7 @@ export class NansenAPI {
|
|
|
1962
2180
|
}
|
|
1963
2181
|
|
|
1964
2182
|
async pmEventScreener(params = {}) {
|
|
1965
|
-
const { orderBy, sortBy = 'volume_24hr', query = '', status = '', tags, minLiquidity, maxLiquidity,
|
|
2183
|
+
const { orderBy, sortBy = 'volume_24hr', query = '', status = '', tags, minLiquidity, maxLiquidity, maxUniqueTraders24h, minVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, pagination } = params;
|
|
1966
2184
|
const body = {
|
|
1967
2185
|
sort_by: sortBy,
|
|
1968
2186
|
query,
|
|
@@ -1973,10 +2191,8 @@ export class NansenAPI {
|
|
|
1973
2191
|
if (tags && tags.length) body.tags = tags;
|
|
1974
2192
|
if (minLiquidity != null) body.min_liquidity = minLiquidity;
|
|
1975
2193
|
if (maxLiquidity != null) body.max_liquidity = maxLiquidity;
|
|
1976
|
-
if (minUniqueTraders24h != null) body.min_unique_traders_24h = minUniqueTraders24h;
|
|
1977
2194
|
if (maxUniqueTraders24h != null) body.max_unique_traders_24h = maxUniqueTraders24h;
|
|
1978
2195
|
if (minVolume24hr != null) body.min_volume_24hr = minVolume24hr;
|
|
1979
|
-
if (maxVolume24hr != null) body.max_volume_24hr = maxVolume24hr;
|
|
1980
2196
|
if (negRisk != null) body.neg_risk = negRisk;
|
|
1981
2197
|
if (minOpenInterest != null) body.min_open_interest = minOpenInterest;
|
|
1982
2198
|
if (maxOpenInterest != null) body.max_open_interest = maxOpenInterest;
|
|
@@ -2051,7 +2267,7 @@ export class NansenAPI {
|
|
|
2051
2267
|
async researchDexTrades(params = {}) {
|
|
2052
2268
|
const { tokenAddress, chain = 'solana', fromDate, toDate, filters = {}, orderBy, pagination } = params;
|
|
2053
2269
|
if (tokenAddress) requireValidToken(tokenAddress, chain);
|
|
2054
|
-
return this.request('/api/
|
|
2270
|
+
return this.request('/api/v1/tgm/historical-dex-trades', {
|
|
2055
2271
|
token_address: tokenAddress,
|
|
2056
2272
|
chain,
|
|
2057
2273
|
date_range: { from: fromDate, to: toDate },
|
|
@@ -2064,7 +2280,7 @@ export class NansenAPI {
|
|
|
2064
2280
|
async researchPnlLeaderboard(params = {}) {
|
|
2065
2281
|
const { tokenAddress, chain = 'solana', fromDate, toDate, filters = {}, orderBy, pagination } = params;
|
|
2066
2282
|
if (tokenAddress) requireValidToken(tokenAddress, chain);
|
|
2067
|
-
return this.request('/api/
|
|
2283
|
+
return this.request('/api/v1/tgm/historical-pnl-leaderboard', {
|
|
2068
2284
|
token_address: tokenAddress,
|
|
2069
2285
|
chain,
|
|
2070
2286
|
date_range: { from: fromDate, to: toDate },
|
|
@@ -2075,22 +2291,21 @@ export class NansenAPI {
|
|
|
2075
2291
|
}
|
|
2076
2292
|
|
|
2077
2293
|
async researchTokenFlowSummary(params = {}) {
|
|
2078
|
-
//
|
|
2079
|
-
|
|
2294
|
+
// The endpoint returns one aggregated row: it takes no pagination,
|
|
2295
|
+
// filters or order_by.
|
|
2296
|
+
const { tokenAddress, chain = 'solana', fromDate, toDate } = params;
|
|
2080
2297
|
if (tokenAddress) requireValidToken(tokenAddress, chain);
|
|
2081
|
-
return this.request('/api/
|
|
2298
|
+
return this.request('/api/v1/tgm/historical-token-flow-summary', {
|
|
2082
2299
|
token_address: tokenAddress,
|
|
2083
2300
|
chain,
|
|
2084
2301
|
date_range: { from: fromDate, to: toDate },
|
|
2085
|
-
filters,
|
|
2086
|
-
order_by: orderBy,
|
|
2087
2302
|
});
|
|
2088
2303
|
}
|
|
2089
2304
|
|
|
2090
2305
|
async researchTokenQuantScores(params = {}) {
|
|
2091
2306
|
const { tokenAddress, chain = 'solana', asOfDate, filters = {}, orderBy, pagination } = params;
|
|
2092
2307
|
if (tokenAddress) requireValidToken(tokenAddress, chain);
|
|
2093
|
-
return this.request('/api/
|
|
2308
|
+
return this.request('/api/v1/tgm/historical-token-quant-scores', {
|
|
2094
2309
|
token_address: tokenAddress,
|
|
2095
2310
|
chain,
|
|
2096
2311
|
as_of_date: asOfDate,
|
|
@@ -2103,7 +2318,7 @@ export class NansenAPI {
|
|
|
2103
2318
|
async researchTopHolders(params = {}) {
|
|
2104
2319
|
const { tokenAddress, chain = 'solana', asOfDate, filters = {}, orderBy, pagination } = params;
|
|
2105
2320
|
if (tokenAddress) requireValidToken(tokenAddress, chain);
|
|
2106
|
-
return this.request('/api/
|
|
2321
|
+
return this.request('/api/v1/tgm/historical-top-holders', {
|
|
2107
2322
|
token_address: tokenAddress,
|
|
2108
2323
|
chain,
|
|
2109
2324
|
as_of_date: asOfDate,
|
|
@@ -2116,7 +2331,7 @@ export class NansenAPI {
|
|
|
2116
2331
|
async researchWhoBoughtSold(params = {}) {
|
|
2117
2332
|
const { tokenAddress, chain = 'solana', fromDate, toDate, buyOrSell = 'BUY', filters = {}, orderBy, pagination } = params;
|
|
2118
2333
|
if (tokenAddress) requireValidToken(tokenAddress, chain);
|
|
2119
|
-
return this.request('/api/
|
|
2334
|
+
return this.request('/api/v1/tgm/historical-who-bought-sold', {
|
|
2120
2335
|
token_address: tokenAddress,
|
|
2121
2336
|
chain,
|
|
2122
2337
|
buy_or_sell: buyOrSell,
|
|
@@ -2130,7 +2345,7 @@ export class NansenAPI {
|
|
|
2130
2345
|
async researchSmartMoneyBalances(params = {}) {
|
|
2131
2346
|
// API does not support order_by on this endpoint.
|
|
2132
2347
|
const { chains = ['solana'], asOfDate, filters = {}, pagination } = params;
|
|
2133
|
-
return this.request('/api/
|
|
2348
|
+
return this.request('/api/v1/smart-money/historical-token-balances', {
|
|
2134
2349
|
chains,
|
|
2135
2350
|
as_of_date: asOfDate,
|
|
2136
2351
|
filters,
|
|
@@ -2153,7 +2368,7 @@ export class NansenAPI {
|
|
|
2153
2368
|
async researchWalletBalances(params = {}) {
|
|
2154
2369
|
const { address, chain = 'ethereum', asOfDate, filters = {}, orderBy, pagination } = params;
|
|
2155
2370
|
if (address) requireValidAddress(address, chain);
|
|
2156
|
-
return this.request('/api/
|
|
2371
|
+
return this.request('/api/v1/profiler/address/historical-token-balances', {
|
|
2157
2372
|
address,
|
|
2158
2373
|
chain,
|
|
2159
2374
|
as_of_date: asOfDate,
|
|
@@ -2171,13 +2386,13 @@ export class NansenAPI {
|
|
|
2171
2386
|
as_of_date: asOfDate,
|
|
2172
2387
|
};
|
|
2173
2388
|
if (blockTimestamp) body.block_timestamp = blockTimestamp;
|
|
2174
|
-
return this.request('/api/
|
|
2389
|
+
return this.request('/api/v1/profiler/historical-transaction-lookup', body);
|
|
2175
2390
|
}
|
|
2176
2391
|
|
|
2177
2392
|
async researchWalletTransactions(params = {}) {
|
|
2178
2393
|
const { address, chain = 'ethereum', asOfDate, filters = {}, orderBy, pagination } = params;
|
|
2179
2394
|
if (address) requireValidAddress(address, chain);
|
|
2180
|
-
return this.request('/api/
|
|
2395
|
+
return this.request('/api/v1/profiler/address/historical-transactions', {
|
|
2181
2396
|
address,
|
|
2182
2397
|
chain,
|
|
2183
2398
|
as_of_date: asOfDate,
|