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
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { authDirectory } from '../auth-credentials.js';
|
|
5
|
+
import { feedbackExpiry, withFeedbackJournal } from '../feedback-journal.js';
|
|
6
|
+
import { NansenError, ErrorCode, packageVersion, telemetryHeaders, sleep, statusToErrorCode } from '../api.js';
|
|
7
|
+
import { traceError, traceRequest, traceResponse, traceRetry } from '../debug.js';
|
|
8
|
+
|
|
9
|
+
const PATH = '/api/v1/feedback';
|
|
10
|
+
const TEMPORARY = new Set([429, 500, 502, 503, 504]);
|
|
11
|
+
const ERROR_FIELDS = ['error', 'message', 'code', 'status', 'request_id', 'doc_url', 'param', 'reason', 'retry_after', 'quota', 'errors'];
|
|
12
|
+
|
|
13
|
+
function requestId(response) {
|
|
14
|
+
return response?.headers.get('x-request-id') ?? response?.headers.get('x-kong-request-id') ?? null;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Server messages do not always end with a full stop, and CLI guidance follows them.
|
|
18
|
+
function sentence(text) {
|
|
19
|
+
const value = String(text).trim();
|
|
20
|
+
return /[.!?]$/.test(value) ? value : `${value}.`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function accountAuthOnly(api) {
|
|
24
|
+
if (Object.keys(api.defaultHeaders).length) {
|
|
25
|
+
throw new NansenError('Feedback uses account authentication only. Remove --x402-payment-signature.', ErrorCode.INVALID_PARAMS);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function preserveUncertainSubmission(error, pending) {
|
|
30
|
+
return new NansenError(`${sentence(error.message)} ${pending.message}`, pending.code, error.status ?? pending.status,
|
|
31
|
+
{ ...error.details, ...pending.details, request_id: error.details?.request_id ?? pending.details.request_id, outcome: 'unknown' });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function storageRecoveryError(error, submissionId, unknown = true) {
|
|
35
|
+
return new NansenError(`Private feedback recovery storage is unavailable. ${unknown ? 'The submission may have been saved.' : 'The report was not sent.'} Repair ~/.nansen/feedback, then retry safely with: nansen feedback resume.`,
|
|
36
|
+
error.code, error.status, { ...error.details, submission_id: submissionId, retry_command: 'nansen feedback resume', outcome: unknown ? 'unknown' : 'rejected' });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function clearRejectedFeedback(journal, error, submissionId) {
|
|
40
|
+
try { journal.clear(); }
|
|
41
|
+
catch {
|
|
42
|
+
const message = error.code === 'feedback_blocked' ? 'The report was blocked before reaching Nansen. No report was saved.' : error.message;
|
|
43
|
+
throw new NansenError(`${sentence(message)} Local retry data could not be erased. Repair ~/.nansen/feedback, then run: nansen feedback forget before using --new with the corrected --file.`,
|
|
44
|
+
error.code, error.status, { ...error.details, submission_id: submissionId, outcome: 'rejected', retry_command: 'nansen feedback forget' });
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function required(value, name, usage, hint = '') {
|
|
49
|
+
if (typeof value !== 'string' || !value.trim()) {
|
|
50
|
+
throw new NansenError(`${name} is required. Use: ${usage}.${hint}`, ErrorCode.MISSING_PARAM);
|
|
51
|
+
}
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function retryDelay(response, data, attempt, retry) {
|
|
56
|
+
const header = response?.headers.get('retry-after');
|
|
57
|
+
const headerDelay = header && /^\d+(\.\d+)?$/.test(header.trim())
|
|
58
|
+
? Number(header) * 1000 : header ? Date.parse(header) - Date.now() : NaN;
|
|
59
|
+
const advertised = Number.isFinite(headerDelay) ? headerDelay :
|
|
60
|
+
Number.isFinite(data?.retry_after) && data.retry_after >= 0 ? data.retry_after * 1000 : NaN;
|
|
61
|
+
return Math.max(Math.min(retry.maxDelayMs, retry.baseDelayMs * 2 ** attempt), Number.isFinite(advertised) ? Math.max(0, advertised) : 0);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function redactor(credentials) {
|
|
65
|
+
const secrets = Object.values(credentials).flatMap(value => [value, value.replace(/^Bearer /, '')]);
|
|
66
|
+
const redact = value => {
|
|
67
|
+
if (typeof value === 'string') return secrets.reduce((text, secret) => secret ? text.split(secret).join('[redacted]') : text, value);
|
|
68
|
+
if (Array.isArray(value)) return value.map(redact);
|
|
69
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redact(item)]));
|
|
70
|
+
return value;
|
|
71
|
+
};
|
|
72
|
+
return redact;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Undici quotes a rejected header value in its message, so a malformed key would reach the trace.
|
|
76
|
+
function transportFailure(error) {
|
|
77
|
+
const code = error?.cause?.code;
|
|
78
|
+
return typeof code === 'string' && /^[A-Z][A-Z0-9_]*$/.test(code) ? code : error?.name ?? 'Error';
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Feedback keeps the file bytes and uses selected account credentials. It never
|
|
82
|
+
// enters the generic client's body cleaning, cache, pagination or payment paths.
|
|
83
|
+
async function requestFeedback(api, endpoint, body, submissionId, { preference = false, previouslyUncertain = false, managed = false } = {}) {
|
|
84
|
+
accountAuthOnly(api);
|
|
85
|
+
const retry = api.retryOptions;
|
|
86
|
+
const maxRetries = Math.min(retry.maxRetries, 3);
|
|
87
|
+
const method = body === undefined ? 'GET' : 'POST', url = `${api.baseUrl}${endpoint}`;
|
|
88
|
+
// A generated ID is recovered with `nansen feedback resume`, which the caller adds.
|
|
89
|
+
const retryHint = managed ? '' : ' Retry the same --submission-id with the unchanged --file.';
|
|
90
|
+
const keepHint = managed ? '' : ' Keep the same --submission-id and unchanged --file for recovery.';
|
|
91
|
+
let lastError;
|
|
92
|
+
let uncertainSubmission = previouslyUncertain ? new NansenError(
|
|
93
|
+
`An earlier attempt may have been saved.${keepHint}`,
|
|
94
|
+
'submission_outcome_unknown', null,
|
|
95
|
+
{ reason: 'submission_outcome_unknown', submission_id: submissionId, outcome: 'unknown' },
|
|
96
|
+
) : undefined;
|
|
97
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
98
|
+
let credentials;
|
|
99
|
+
try { credentials = await api.requestCredentials({}); } catch (error) {
|
|
100
|
+
if (!uncertainSubmission) throw error;
|
|
101
|
+
throw preserveUncertainSubmission(error, uncertainSubmission);
|
|
102
|
+
}
|
|
103
|
+
if (!Object.keys(credentials).length) {
|
|
104
|
+
throw new NansenError('Not logged in. Run: nansen login, or set NANSEN_API_KEY.', ErrorCode.UNAUTHORIZED);
|
|
105
|
+
}
|
|
106
|
+
const redact = redactor(credentials);
|
|
107
|
+
let response, data;
|
|
108
|
+
api.beforeFeedbackRequest?.();
|
|
109
|
+
const startedAt = Date.now();
|
|
110
|
+
traceRequest({ method, url, attempt: attempt + 1, maxAttempts: maxRetries + 1 });
|
|
111
|
+
try {
|
|
112
|
+
response = await fetch(url, {
|
|
113
|
+
method, redirect: 'error', cache: 'no-store',
|
|
114
|
+
signal: AbortSignal.timeout(30000),
|
|
115
|
+
headers: {
|
|
116
|
+
'X-Client-Type': 'nansen-cli', 'X-Client-Version': packageVersion,
|
|
117
|
+
...telemetryHeaders(), ...credentials,
|
|
118
|
+
...(body !== undefined && { 'Content-Type': 'application/json', 'Idempotency-Key': submissionId }),
|
|
119
|
+
},
|
|
120
|
+
...(body !== undefined && { body }),
|
|
121
|
+
}).catch(error => {
|
|
122
|
+
traceError({ method, url, durationMs: Date.now() - startedAt, attempt: attempt + 1, error: transportFailure(error) });
|
|
123
|
+
throw error;
|
|
124
|
+
});
|
|
125
|
+
traceResponse({ method, url, status: response.status, durationMs: Date.now() - startedAt, requestId: requestId(response), attempt: attempt + 1 });
|
|
126
|
+
data = await response.json();
|
|
127
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('Invalid response');
|
|
128
|
+
if (response.ok) {
|
|
129
|
+
if (preference) {
|
|
130
|
+
if (!['enabled', 'disabled'].includes(data.automatic_reporting) || typeof data.configured !== 'boolean' ||
|
|
131
|
+
!Number.isSafeInteger(data.version) || data.version < 0 || typeof data.can_manage !== 'boolean' ||
|
|
132
|
+
!(data.updated_at === null || (typeof data.updated_at === 'string' && Number.isFinite(Date.parse(data.updated_at)))) ||
|
|
133
|
+
(!data.configured && data.automatic_reporting !== 'disabled')) throw new Error('Invalid preference');
|
|
134
|
+
return Object.fromEntries(['automatic_reporting', 'configured', 'version', 'updated_at', 'can_manage'].map(key => [key, data[key]]));
|
|
135
|
+
}
|
|
136
|
+
if (typeof data.feedback_id !== 'string' || typeof data.submission_id !== 'string' ||
|
|
137
|
+
!['received', 'reviewed', 'closed'].includes(data.status) ||
|
|
138
|
+
(submissionId && data.submission_id !== submissionId)) throw new Error('Invalid receipt');
|
|
139
|
+
return redact(data);
|
|
140
|
+
}
|
|
141
|
+
} catch {
|
|
142
|
+
if (body !== undefined && response?.status === 403 && response.headers.get('content-type')?.split(';')[0].trim().toLowerCase() === 'text/html') {
|
|
143
|
+
const blocked = new NansenError(uncertainSubmission
|
|
144
|
+
? 'This attempt was blocked before reaching Nansen.'
|
|
145
|
+
: `The report was blocked before reaching Nansen. No report was saved.${managed ? '' : ' Change the report and use a new submission ID.'}`,
|
|
146
|
+
'feedback_blocked', 403,
|
|
147
|
+
{ reason: 'feedback_blocked', outcome: 'rejected', submission_id: submissionId, request_id: redact(requestId(response)) });
|
|
148
|
+
if (uncertainSubmission) throw preserveUncertainSubmission(blocked, uncertainSubmission);
|
|
149
|
+
throw blocked;
|
|
150
|
+
}
|
|
151
|
+
if (response && [402, 404, 501].includes(response.status)) {
|
|
152
|
+
const unavailable = new NansenError('Feedback is unavailable on this backend. Retry after feedback support is deployed.', 'feedback_unavailable', response.status,
|
|
153
|
+
{ submission_id: submissionId ?? null, request_id: redact(requestId(response)) });
|
|
154
|
+
if (uncertainSubmission) throw preserveUncertainSubmission(unavailable, uncertainSubmission);
|
|
155
|
+
throw unavailable;
|
|
156
|
+
}
|
|
157
|
+
const unknown = body !== undefined;
|
|
158
|
+
lastError = new NansenError(
|
|
159
|
+
unknown ? `The submission may have been saved.${retryHint}` : preference ? 'Feedback preference unavailable. Show the report and ask before sending.' : 'Receipt lookup failed. Retry nansen feedback get with the same feedback ID.',
|
|
160
|
+
unknown ? 'submission_outcome_unknown' : ErrorCode.NETWORK_ERROR, response?.status ?? null,
|
|
161
|
+
{ reason: unknown ? 'submission_outcome_unknown' : preference ? 'preference_unavailable' : 'receipt_unavailable', submission_id: submissionId ?? null, request_id: redact(requestId(response)), ...(unknown && { outcome: 'unknown' }) },
|
|
162
|
+
);
|
|
163
|
+
if (unknown) uncertainSubmission = lastError;
|
|
164
|
+
if (attempt < maxRetries && (!response || response.ok || TEMPORARY.has(response.status))) {
|
|
165
|
+
const delay = retryDelay(response, null, attempt, retry);
|
|
166
|
+
if (delay <= retry.maxRetryAfterMs) {
|
|
167
|
+
traceRetry({ method, url, status: response?.status, attempt: attempt + 1, reason: response ? 'unparseable-response' : 'network-error', delayMs: delay });
|
|
168
|
+
await sleep(delay); continue;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
throw lastError;
|
|
172
|
+
}
|
|
173
|
+
const details = redact(Object.fromEntries(ERROR_FIELDS.filter(key => key in data).map(key => [key, data[key]])));
|
|
174
|
+
details.request_id ??= redact(requestId(response));
|
|
175
|
+
if (submissionId) details.submission_id = submissionId;
|
|
176
|
+
if (uncertainSubmission && data.reason !== 'feedback_erased') details.outcome = 'unknown';
|
|
177
|
+
if (response.status === 403 && data.reason === 'feedback_not_enabled') {
|
|
178
|
+
const uncertainty = uncertainSubmission ? ` An earlier attempt may have been saved.${keepHint}` : '';
|
|
179
|
+
throw new NansenError(`Feedback is not enabled for this account. Stop automatic retries. User approval or an enabled preference does not override rollout.${uncertainty}`,
|
|
180
|
+
uncertainSubmission ? uncertainSubmission.code : details.code || 'forbidden', response.status,
|
|
181
|
+
{ ...details, outcome: uncertainSubmission ? 'unknown' : 'rejected' });
|
|
182
|
+
}
|
|
183
|
+
const unavailable = response.status === 402 || data.code === 'insufficient_credits' || response.status === 501 ||
|
|
184
|
+
(response.status === 404 && body !== undefined);
|
|
185
|
+
if (unavailable) {
|
|
186
|
+
const error = new NansenError('Feedback is unavailable on this backend. Retry after feedback support is deployed; no payment or account switch was attempted.', 'feedback_unavailable', response.status, details);
|
|
187
|
+
if (uncertainSubmission) throw preserveUncertainSubmission(error, uncertainSubmission);
|
|
188
|
+
throw error;
|
|
189
|
+
}
|
|
190
|
+
if (response.status === 404) {
|
|
191
|
+
if (preference) throw new NansenError('Feedback preference unavailable on this backend. Show the report and ask before sending.', 'feedback_unavailable', response.status, details);
|
|
192
|
+
throw new NansenError('Receipt not found, or this backend does not support feedback yet. Check the feedback ID, active account and NANSEN_BASE_URL. Do not resubmit as a new report.', details.code || 'not_found', response.status, details);
|
|
193
|
+
}
|
|
194
|
+
lastError = new NansenError(details.message || 'Feedback request failed.', details.code || statusToErrorCode(response.status, data), response.status, details);
|
|
195
|
+
if (body !== undefined && response.status >= 500 && data.reason !== 'feedback_admissions_paused') {
|
|
196
|
+
uncertainSubmission ??= new NansenError(`The submission may have been saved.${retryHint}`,
|
|
197
|
+
'submission_outcome_unknown', response.status,
|
|
198
|
+
{ reason: 'submission_outcome_unknown', submission_id: submissionId, request_id: details.request_id });
|
|
199
|
+
}
|
|
200
|
+
if (uncertainSubmission && [401, 403].includes(response.status)) throw preserveUncertainSubmission(lastError, uncertainSubmission);
|
|
201
|
+
const weekly = data.reason === 'feedback_weekly_quota_exhausted';
|
|
202
|
+
const delay = retryDelay(response, data, attempt, retry);
|
|
203
|
+
if (!weekly && TEMPORARY.has(response.status) && attempt < maxRetries && delay <= retry.maxRetryAfterMs) {
|
|
204
|
+
traceRetry({ method, url, status: response.status, attempt: attempt + 1, reason: 'retryable-status', delayMs: delay });
|
|
205
|
+
await sleep(delay);
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
if (uncertainSubmission && response.status >= 500) {
|
|
209
|
+
throw new NansenError(`${sentence(lastError.message)} ${uncertainSubmission.message}`, uncertainSubmission.code,
|
|
210
|
+
response.status, { ...details, outcome: 'unknown' });
|
|
211
|
+
}
|
|
212
|
+
throw lastError;
|
|
213
|
+
}
|
|
214
|
+
throw lastError;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// Resolve the account from the server, then freeze those exact credentials for
|
|
218
|
+
// the entire operation. Re-login in another process cannot redirect a replay.
|
|
219
|
+
async function feedbackIdentity(api) {
|
|
220
|
+
accountAuthOnly(api);
|
|
221
|
+
const credentials = await api.requestCredentials({});
|
|
222
|
+
if (!Object.keys(credentials).length) throw new NansenError('Not logged in. Run: nansen login, or set NANSEN_API_KEY.', ErrorCode.UNAUTHORIZED);
|
|
223
|
+
let response, data;
|
|
224
|
+
try {
|
|
225
|
+
const environment = new URL(api.baseUrl).href.replace(/\/$/, '');
|
|
226
|
+
const url = `${environment}/api/v1/account`, startedAt = Date.now();
|
|
227
|
+
traceRequest({ method: 'GET', url, attempt: 1 });
|
|
228
|
+
response = await fetch(url, { headers: credentials, redirect: 'error', cache: 'no-store', signal: AbortSignal.timeout(15000) }).catch(error => {
|
|
229
|
+
traceError({ method: 'GET', url, durationMs: Date.now() - startedAt, attempt: 1, error: transportFailure(error) });
|
|
230
|
+
throw error;
|
|
231
|
+
});
|
|
232
|
+
traceResponse({ method: 'GET', url, status: response.status, durationMs: Date.now() - startedAt, requestId: requestId(response), attempt: 1 });
|
|
233
|
+
data = await response.json();
|
|
234
|
+
if (!response.ok || typeof data.user_id !== 'string' || !data.user_id || data.user_id.length > 255 || [...data.user_id].some(c => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127)) throw new Error();
|
|
235
|
+
return { account: data.user_id, environment, api: { ...api, baseUrl: environment, requestCredentials: async () => credentials } };
|
|
236
|
+
} catch {
|
|
237
|
+
// A rejected credential is not an account or environment change. An HTML 403 is an edge block, not a key problem.
|
|
238
|
+
if (response?.status === 401 || (response?.status === 403 && typeof data?.message === 'string')) {
|
|
239
|
+
const redact = redactor(credentials);
|
|
240
|
+
const reason = typeof data?.message === 'string' && data.message.trim() ? redact(data.message) : `HTTP ${response.status}`;
|
|
241
|
+
// Any key may read the account, so a JSON 403 refuses the account itself and another key would not help.
|
|
242
|
+
const next = response.status === 401 ? 'Use a valid API key or login for the original account, then retry.' : "Check this account's access, then retry.";
|
|
243
|
+
throw new NansenError(`${sentence(reason)} Could not verify the feedback account. No report was sent. ${next}`,
|
|
244
|
+
'feedback_identity_unverified', response.status, { request_id: redact(requestId(response)) });
|
|
245
|
+
}
|
|
246
|
+
throw new NansenError('Could not verify the feedback account. No report was sent. Retry with the original account and NANSEN_BASE_URL.', 'feedback_identity_unverified');
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async function managedFeedback(api, { body, newSubmission = false, forget = false } = {}) {
|
|
251
|
+
return withFeedbackJournal(async journal => {
|
|
252
|
+
let entry = journal.entry;
|
|
253
|
+
if (forget) { journal.clear(); return { forgotten: true }; }
|
|
254
|
+
if (newSubmission && entry?.state === 'pending') throw new NansenError('A submission is still pending. Run: nansen feedback resume. To erase its local retry data, run: nansen feedback forget.', 'feedback_pending');
|
|
255
|
+
if ((!entry && body === undefined) || (entry?.state === 'cleared' && !newSubmission)) throw new NansenError('No replayable feedback remains. Expired or erased submissions are never replayed. Use --new only for a deliberate new report.', 'feedback_recovery_unavailable');
|
|
256
|
+
if (entry?.state === 'confirmed' && body !== undefined && !newSubmission) throw new NansenError('The previous submission has a confirmed receipt. Run: nansen feedback resume. Use --new only for a deliberate new report.', 'feedback_already_confirmed');
|
|
257
|
+
if (entry && !newSubmission && new URL(api.baseUrl).href.replace(/\/$/, '') !== entry.environment) throw new NansenError('The API environment changed. Restore the original NANSEN_BASE_URL, then run: nansen feedback resume.', 'feedback_identity_mismatch');
|
|
258
|
+
if (entry?.state === 'pending' && body !== undefined && body !== entry.body) throw new NansenError('The report changed. Run: nansen feedback resume to retry the saved, unchanged report, or nansen feedback forget to erase its local retry data before a deliberate --new submission.', 'feedback_report_changed');
|
|
259
|
+
const identity = await feedbackIdentity(api);
|
|
260
|
+
if (entry && !newSubmission && identity.account !== entry.account) throw new NansenError('The Nansen account changed. Log in to the original account, then run: nansen feedback resume.', 'feedback_identity_mismatch');
|
|
261
|
+
if (!entry || newSubmission) {
|
|
262
|
+
entry = { version: 1, state: 'pending', submission_id: randomUUID(), account: identity.account, environment: identity.environment, expires_at: feedbackExpiry(Date.now()), body, uncertain: false };
|
|
263
|
+
try { journal.save(entry); }
|
|
264
|
+
catch (error) {
|
|
265
|
+
// The journal may already exist even if its directory sync failed.
|
|
266
|
+
if (error.journalSaved) throw storageRecoveryError(error, entry.submission_id, false);
|
|
267
|
+
throw error;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
// Older journals cannot distinguish a denial from a lost response.
|
|
271
|
+
const previouslyUncertain = entry.state === 'pending' && entry.uncertain !== false;
|
|
272
|
+
let dispatched = false;
|
|
273
|
+
identity.api.beforeFeedbackRequest = () => {
|
|
274
|
+
if (Date.parse(entry.expires_at) <= Date.now()) {
|
|
275
|
+
journal.clear();
|
|
276
|
+
throw new NansenError('Saved feedback expired and was erased. It will not be replayed.', 'feedback_recovery_unavailable');
|
|
277
|
+
}
|
|
278
|
+
if (entry.state === 'pending' && !dispatched) {
|
|
279
|
+
// A crash after dispatch must never turn a possible acceptance into a rejection.
|
|
280
|
+
journal.save({ ...entry, uncertain: true });
|
|
281
|
+
dispatched = true;
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
try {
|
|
285
|
+
const receipt = entry.state === 'confirmed'
|
|
286
|
+
? await requestFeedback(identity.api, `${PATH}/${encodeURIComponent(entry.feedback_id)}`, undefined, entry.submission_id)
|
|
287
|
+
: await requestFeedback(identity.api, PATH, entry.body, entry.submission_id, { previouslyUncertain, managed: true });
|
|
288
|
+
const expiry = Date.parse(receipt.expires_at);
|
|
289
|
+
if (!Number.isFinite(expiry)) throw new NansenError('The receipt expiry could not be confirmed. The submission may have been saved.', 'submission_outcome_unknown');
|
|
290
|
+
// Never retain the body, its digest, or any free-text receipt fields.
|
|
291
|
+
journal.save({ version: 1, state: 'confirmed', submission_id: entry.submission_id, account: entry.account, environment: entry.environment,
|
|
292
|
+
expires_at: new Date(Math.min(expiry, Date.parse(entry.expires_at))).toISOString(), feedback_id: receipt.feedback_id });
|
|
293
|
+
return receipt;
|
|
294
|
+
} catch (error) {
|
|
295
|
+
if (error.details?.reason === 'feedback_erased') { clearRejectedFeedback(journal, error, entry.submission_id); throw error; }
|
|
296
|
+
if (entry.state === 'confirmed' && error.status === 404) {
|
|
297
|
+
try { journal.clear(); } catch (storageError) { throw storageRecoveryError(storageError, entry.submission_id); }
|
|
298
|
+
throw error;
|
|
299
|
+
}
|
|
300
|
+
if (entry.state !== 'pending' || error.code === 'feedback_recovery_unavailable') throw error;
|
|
301
|
+
if (error.code === 'feedback_storage_unavailable') throw storageRecoveryError(error, entry.submission_id, dispatched || previouslyUncertain);
|
|
302
|
+
const unknown = previouslyUncertain || error.code === 'submission_outcome_unknown' || error.details?.outcome === 'unknown';
|
|
303
|
+
if (!unknown && ([400, 413, 422].includes(error.status) || (error.status === 409 && error.details?.reason === 'idempotency_key_reused') ||
|
|
304
|
+
error.code === 'feedback_blocked')) {
|
|
305
|
+
clearRejectedFeedback(journal, error, entry.submission_id);
|
|
306
|
+
throw new NansenError(`${sentence(error.message)} This attempt was rejected. Local retry data was erased. Correct the report and use --new with the corrected --file.`,
|
|
307
|
+
error.code, error.status, { ...error.details, submission_id: entry.submission_id, outcome: 'rejected' });
|
|
308
|
+
}
|
|
309
|
+
try { journal.save({ ...entry, uncertain: unknown }); }
|
|
310
|
+
catch (error) { throw storageRecoveryError(error, entry.submission_id, dispatched || previouslyUncertain); }
|
|
311
|
+
if (error.status === 403 && error.details?.reason === 'feedback_not_enabled') {
|
|
312
|
+
const outcomeText = unknown ? '' : ' This report was not accepted.';
|
|
313
|
+
throw new NansenError(`${error.message}${outcomeText} The saved ID and report are retained for recovery.`,
|
|
314
|
+
error.code, error.status, { ...error.details, submission_id: entry.submission_id, outcome: unknown ? 'unknown' : 'rejected' });
|
|
315
|
+
}
|
|
316
|
+
if (error.status === 429 && error.details?.reason === 'feedback_weekly_quota_exhausted') {
|
|
317
|
+
throw new NansenError(`${sentence(error.message)} ${unknown ? 'An earlier attempt may have been accepted.' : 'This submission was not accepted.'} Wait for the weekly reset before running: nansen feedback resume.`,
|
|
318
|
+
error.code, error.status, { ...error.details, submission_id: entry.submission_id, outcome: unknown ? 'unknown' : 'rejected',
|
|
319
|
+
retry_command: 'nansen feedback resume', retry_not_before: error.details.quota?.resets_at ?? null });
|
|
320
|
+
}
|
|
321
|
+
// submission_outcome_unknown messages already say the submission may have been saved.
|
|
322
|
+
const recovery = unknown
|
|
323
|
+
? `${error.code === 'submission_outcome_unknown' ? '' : 'The saved submission may have been accepted. '}Retry safely with: nansen feedback resume.`
|
|
324
|
+
: 'This report was not accepted. Retry the saved report with: nansen feedback resume.';
|
|
325
|
+
throw new NansenError(`${sentence(error.message)} ${recovery}`,
|
|
326
|
+
error.code, error.status, { ...error.details, submission_id: entry.submission_id, retry_command: 'nansen feedback resume', outcome: unknown ? 'unknown' : 'rejected' });
|
|
327
|
+
}
|
|
328
|
+
}, { erase: forget });
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function receiptText(receipt) {
|
|
332
|
+
const wording = {
|
|
333
|
+
received: 'Received. Your report is saved; human review may still be pending.',
|
|
334
|
+
reviewed: 'Reviewed. A teammate has triaged your report; no fix or date is promised.',
|
|
335
|
+
closed: `Closed. Review is complete. Disposition: ${receipt.disposition ?? 'unspecified'}.`,
|
|
336
|
+
};
|
|
337
|
+
return [wording[receipt.status], `Feedback ID: ${receipt.feedback_id}`, `Submission ID: ${receipt.submission_id}`,
|
|
338
|
+
...(receipt.replayed ? ['Replay accepted; no new report slot was consumed.'] : []),
|
|
339
|
+
...(receipt.quota ? [`Weekly allowance: ${receipt.quota.remaining}/${receipt.quota.limit} remaining. Resets: ${receipt.quota.resets_at}`] : [])].join('\n');
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export function feedbackErrorText(error) {
|
|
343
|
+
const details = error.details ?? {};
|
|
344
|
+
return [error.message, ...(details.quota?.resets_at ? [`Quota resets: ${details.quota.resets_at}`] : []),
|
|
345
|
+
...(Array.isArray(details.errors) ? details.errors.filter(item => typeof item?.field === 'string' && typeof item.code === 'string')
|
|
346
|
+
.map(item => `${item.field}: ${item.code}`) : []),
|
|
347
|
+
...(details.retry_after !== undefined ? [`Retry after: ${details.retry_after} seconds`] : []),
|
|
348
|
+
...(details.submission_id ? [`Submission ID: ${details.submission_id}`] : []),
|
|
349
|
+
...(details.request_id ? [`Request ID: ${details.request_id}`] : [])].join('\n');
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
export function buildFeedbackCommands({ log = console.log } = {}) {
|
|
353
|
+
return {
|
|
354
|
+
feedback: async (args, api, flags, options) => {
|
|
355
|
+
let receipt;
|
|
356
|
+
if (flags['submission-id']) throw new NansenError('--submission-id requires a value.', ErrorCode.INVALID_PARAMS);
|
|
357
|
+
if (args[0] === 'preferences') {
|
|
358
|
+
if (args.length !== 1 || options.file || options['submission-id'] || flags.new) throw new NansenError('Use: nansen feedback preferences [--json]', ErrorCode.INVALID_PARAMS);
|
|
359
|
+
accountAuthOnly(api);
|
|
360
|
+
try { receipt = await requestFeedback(api, `${PATH}/preferences`, undefined, undefined, { preference: true }); }
|
|
361
|
+
catch (error) {
|
|
362
|
+
const guidance = 'Feedback preference unavailable. Show the report and ask before sending.';
|
|
363
|
+
// Local failures and rejected credentials tell the user what to fix; other HTTP failures only need the guidance.
|
|
364
|
+
const cause = (error.status == null || [401, 403].includes(error.status)) && error.message !== guidance ? ` ${error.message}` : '';
|
|
365
|
+
throw new NansenError(`${guidance}${cause}`, error.code, error.status,
|
|
366
|
+
{ ...error.details, reason: 'preference_unavailable' });
|
|
367
|
+
}
|
|
368
|
+
if (flags.json || flags.pretty || flags.p) return receipt;
|
|
369
|
+
log(`Automatic feedback: ${receipt.automatic_reporting}${receipt.configured ? '' : ' (not configured)'}.\n${receipt.automatic_reporting === 'enabled' ? 'Agents may send without asking, subject to host controls and account rollout.' : 'Show the report and ask before sending.'}\nChange the lasting choice in Superapp settings. Approval for one report does not change it.`);
|
|
370
|
+
return;
|
|
371
|
+
} else if (args[0] === 'submit') {
|
|
372
|
+
if (args.length !== 1) throw new NansenError('Use: nansen feedback submit --file feedback.json [--submission-id <new-id> | --new] [--json]', ErrorCode.INVALID_PARAMS);
|
|
373
|
+
const id = options['submission-id'];
|
|
374
|
+
if (id !== undefined && flags.new) throw new NansenError('Use either --new or --submission-id.', ErrorCode.INVALID_PARAMS);
|
|
375
|
+
if (id !== undefined && (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id))) throw new NansenError('--submission-id must contain 1 to 128 ASCII letters, digits, underscores or hyphens.', ErrorCode.INVALID_PARAMS);
|
|
376
|
+
const file = required(options.file, '--file', 'nansen feedback submit --file feedback.json --submission-id <new-id>',
|
|
377
|
+
' Reuse the submission ID and unchanged file after an uncertain submission result.');
|
|
378
|
+
let body;
|
|
379
|
+
try { body = fs.readFileSync(file, 'utf8'); } catch { throw new NansenError('Cannot read --file. Supply a readable JSON report file.', ErrorCode.INVALID_PARAMS); }
|
|
380
|
+
let report;
|
|
381
|
+
try { report = JSON.parse(body); } catch { throw new NansenError('--file must contain valid JSON.', ErrorCode.INVALID_PARAMS); }
|
|
382
|
+
if (!report || typeof report !== 'object' || Array.isArray(report)) throw new NansenError('--file must contain a JSON report object.', ErrorCode.INVALID_PARAMS);
|
|
383
|
+
if (Buffer.byteLength(body) > 16384) throw new NansenError('The report exceeds 16 KiB.', ErrorCode.INVALID_PARAMS);
|
|
384
|
+
receipt = id !== undefined ? await requestFeedback(api, PATH, body, id) : await managedFeedback(api, { body, newSubmission: flags.new === true });
|
|
385
|
+
} else if (args[0] === 'resume' || args[0] === 'forget') {
|
|
386
|
+
if (args.length !== 1 || options.file || options['submission-id'] || flags.new) throw new NansenError(`Use: nansen feedback ${args[0]} [--json]`, ErrorCode.INVALID_PARAMS);
|
|
387
|
+
receipt = await managedFeedback(api, { forget: args[0] === 'forget' });
|
|
388
|
+
} else if (args[0] === 'get') {
|
|
389
|
+
const id = required(args[1], 'Feedback ID', 'nansen feedback get <feedback-id> [--json]');
|
|
390
|
+
if (args.length !== 2) throw new NansenError('Use: nansen feedback get <feedback-id> [--json]', ErrorCode.INVALID_PARAMS);
|
|
391
|
+
const local = path.join(authDirectory(), 'feedback', 'recovery.json');
|
|
392
|
+
if (fs.lstatSync(local, { throwIfNoEntry: false })) {
|
|
393
|
+
receipt = await withFeedbackJournal(async journal => {
|
|
394
|
+
if (journal.entry?.state !== 'confirmed' || journal.entry.feedback_id !== id) return requestFeedback(api, `${PATH}/${encodeURIComponent(id)}`);
|
|
395
|
+
const identity = await feedbackIdentity(api);
|
|
396
|
+
if (identity.account !== journal.entry.account || identity.environment !== journal.entry.environment) throw new NansenError('Use the original account and NANSEN_BASE_URL to read the saved receipt.', 'feedback_identity_mismatch');
|
|
397
|
+
try { return await requestFeedback(identity.api, `${PATH}/${encodeURIComponent(id)}`, undefined, journal.entry.submission_id); }
|
|
398
|
+
catch (error) {
|
|
399
|
+
if (error.status === 404 || error.details?.reason === 'feedback_erased') {
|
|
400
|
+
try { journal.clear(); } catch (storageError) { throw storageRecoveryError(storageError, journal.entry.submission_id); }
|
|
401
|
+
}
|
|
402
|
+
throw error;
|
|
403
|
+
}
|
|
404
|
+
});
|
|
405
|
+
} else receipt = await requestFeedback(api, `${PATH}/${encodeURIComponent(id)}`);
|
|
406
|
+
} else {
|
|
407
|
+
throw new NansenError('Use: nansen feedback preferences, nansen feedback submit --file feedback.json, nansen feedback resume, nansen feedback forget, or nansen feedback get <feedback-id>. Add --json for structured output.', ErrorCode.INVALID_PARAMS);
|
|
408
|
+
}
|
|
409
|
+
if (flags.json || flags.pretty || flags.p) return receipt;
|
|
410
|
+
log(receipt.forgotten ? 'Local feedback retry data erased. This does not delete a report already saved by Nansen. Your original input file is unchanged.' : receiptText(receipt));
|
|
411
|
+
},
|
|
412
|
+
};
|
|
413
|
+
}
|
package/src/commands/mcp.js
CHANGED
|
@@ -307,7 +307,7 @@ export function buildMcpCommands(deps = {}) {
|
|
|
307
307
|
}
|
|
308
308
|
|
|
309
309
|
if (sub !== 'install' && sub !== 'uninstall') {
|
|
310
|
-
throw new CommandError(`Unknown subcommand: ${sub}\n\n${MCP_USAGE}`, '
|
|
310
|
+
throw new CommandError(`Unknown subcommand: ${sub}\n\n${MCP_USAGE}`, 'UNKNOWN_COMMAND');
|
|
311
311
|
}
|
|
312
312
|
|
|
313
313
|
requireClient(sub, client);
|
package/src/commands/research.js
CHANGED
|
@@ -5,30 +5,8 @@
|
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
import { NansenError, ErrorCode } from '../api.js';
|
|
8
|
-
import { parseSort, rejectBlankOption,
|
|
9
|
-
|
|
10
|
-
// Research subcommands validate --page strictly. The shared helper in
|
|
11
|
-
// src/query-options.js clamps an invalid page to 1 for the category commands,
|
|
12
|
-
// so keep a local variant here that rejects it instead.
|
|
13
|
-
function buildPagination(options) {
|
|
14
|
-
if (options.limit === undefined && options.page === undefined) return undefined;
|
|
15
|
-
const pagination = { page: 1 };
|
|
16
|
-
if (options.page !== undefined) {
|
|
17
|
-
const page = Number(options.page);
|
|
18
|
-
if (!Number.isInteger(page) || page < 1) {
|
|
19
|
-
throw new NansenError('--page must be a positive integer', ErrorCode.INVALID_PARAMS);
|
|
20
|
-
}
|
|
21
|
-
pagination.page = page;
|
|
22
|
-
}
|
|
23
|
-
if (options.limit !== undefined) {
|
|
24
|
-
const perPage = Number(options.limit);
|
|
25
|
-
if (!Number.isInteger(perPage) || perPage < 1) {
|
|
26
|
-
throw new NansenError('--limit must be a positive integer', ErrorCode.INVALID_PARAMS);
|
|
27
|
-
}
|
|
28
|
-
pagination.per_page = perPage;
|
|
29
|
-
}
|
|
30
|
-
return pagination;
|
|
31
|
-
}
|
|
8
|
+
import { buildPagination, parseSort, rejectBlankOption, parseFiltersOption } from '../query-options.js';
|
|
9
|
+
import { unknownCommandError } from '../input-validation.js';
|
|
32
10
|
|
|
33
11
|
const SUBCOMMANDS = [
|
|
34
12
|
'historical-dex-trades',
|
|
@@ -89,9 +67,9 @@ function parseBooleanOption(options, flags, key) {
|
|
|
89
67
|
|
|
90
68
|
function parseChains(options) {
|
|
91
69
|
if (options.chains) {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
70
|
+
// "a,b", a repeated flag (each value may itself be "a,b") or a JSON array.
|
|
71
|
+
const values = Array.isArray(options.chains) ? options.chains : [options.chains];
|
|
72
|
+
return values.flatMap(value => String(value).split(',')).map(s => s.trim()).filter(Boolean);
|
|
95
73
|
}
|
|
96
74
|
if (options.chain) return [options.chain];
|
|
97
75
|
return undefined;
|
|
@@ -178,7 +156,8 @@ USAGE:
|
|
|
178
156
|
USAGE:
|
|
179
157
|
nansen research historical-token-flow-summary --token-address <addr> --from-date <YYYY-MM-DD> --to-date <YYYY-MM-DD> [--chain <chain>]
|
|
180
158
|
|
|
181
|
-
NOTE: This endpoint does not support pagination
|
|
159
|
+
NOTE: This endpoint does not support pagination.
|
|
160
|
+
Whale, public figure, top PnL and exchange label history starts 2025-03-11, so those fields are null for an earlier --to-date.`,
|
|
182
161
|
'historical-token-quant-scores': `nansen research historical-token-quant-scores — Historical token quantitative scores
|
|
183
162
|
|
|
184
163
|
USAGE:
|
|
@@ -210,7 +189,8 @@ USAGE:
|
|
|
210
189
|
USAGE:
|
|
211
190
|
nansen research historical-tx-lookup --transaction-hash <hash> --as-of-date <YYYY-MM-DD> [--chain <chain>] [--block-timestamp "YYYY-MM-DD HH:MM:SS"]
|
|
212
191
|
|
|
213
|
-
NOTE: Providing --block-timestamp skips a slow hash-resolution step and returns results much faster
|
|
192
|
+
NOTE: Providing --block-timestamp skips a slow hash-resolution step and returns results much faster.
|
|
193
|
+
Entity labels are available from 2025-03-11 onward.`,
|
|
214
194
|
'historical-wallet-transactions': `nansen research historical-wallet-transactions — Historical transactions for a wallet
|
|
215
195
|
|
|
216
196
|
USAGE:
|
|
@@ -218,7 +198,7 @@ USAGE:
|
|
|
218
198
|
'historical-token-ohlcv': `nansen research historical-token-ohlcv — Historical token OHLCV candles
|
|
219
199
|
|
|
220
200
|
USAGE:
|
|
221
|
-
nansen research historical-token-ohlcv --token-address <addr> --from-date <date> --timeframe <5m|15m|30m|1h|1d|1w> (--as-of-date <date> | --as-of-ts <timestamp>) [--chain <chain>] [--apply-blacklist-filter <true|false>]`,
|
|
201
|
+
nansen research historical-token-ohlcv --token-address <addr> --from-date <date> --timeframe <5m|15m|30m|1h|4h|1d|1w> (--as-of-date <date> | --as-of-ts <timestamp>) [--chain <chain>] [--apply-blacklist-filter <true|false>]`,
|
|
222
202
|
};
|
|
223
203
|
|
|
224
204
|
export function buildResearchCommands(deps = {}) {
|
|
@@ -234,10 +214,7 @@ export function buildResearchCommands(deps = {}) {
|
|
|
234
214
|
}
|
|
235
215
|
|
|
236
216
|
if (!RESEARCH_SUBCOMMANDS.has(sub)) {
|
|
237
|
-
throw
|
|
238
|
-
`Unknown research subcommand: ${sub}. Available: ${[...RESEARCH_SUBCOMMANDS].join(', ')}`,
|
|
239
|
-
ErrorCode.UNKNOWN,
|
|
240
|
-
);
|
|
217
|
+
throw unknownCommandError('research subcommand', sub, [...RESEARCH_SUBCOMMANDS]);
|
|
241
218
|
}
|
|
242
219
|
|
|
243
220
|
if (flags.help || flags.h || args[1] === 'help') {
|
|
@@ -256,7 +233,7 @@ export function buildResearchCommands(deps = {}) {
|
|
|
256
233
|
|
|
257
234
|
const orderBy = parseSort(options.sort, options['order-by']);
|
|
258
235
|
const pagination = buildPagination(options);
|
|
259
|
-
const filters =
|
|
236
|
+
const filters = parseFiltersOption(options.filters);
|
|
260
237
|
const { fromDate, toDate } = resolveDateRange(options);
|
|
261
238
|
const asOfDate = options['as-of-date'];
|
|
262
239
|
|
|
@@ -382,7 +359,7 @@ export function buildResearchCommands(deps = {}) {
|
|
|
382
359
|
'historical-token-flow-summary': () => apiInstance.researchTokenFlowSummary({
|
|
383
360
|
tokenAddress: options['token-address'] || options.token,
|
|
384
361
|
chain: options.chain,
|
|
385
|
-
fromDate, toDate,
|
|
362
|
+
fromDate, toDate,
|
|
386
363
|
}),
|
|
387
364
|
'historical-who-bought-sold': () => apiInstance.researchWhoBoughtSold({
|
|
388
365
|
tokenAddress: options['token-address'] || options.token,
|
|
@@ -491,7 +468,7 @@ export function buildResearchCommands(deps = {}) {
|
|
|
491
468
|
}
|
|
492
469
|
|
|
493
470
|
// Should be unreachable because SUBCOMMANDS guarded above.
|
|
494
|
-
throw
|
|
471
|
+
throw unknownCommandError('research subcommand', sub, [...RESEARCH_SUBCOMMANDS]);
|
|
495
472
|
},
|
|
496
473
|
};
|
|
497
474
|
}
|
package/src/cost-cache.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* by an inline fetch of the Nansen OpenAPI spec (at most once per 24h).
|
|
4
4
|
*
|
|
5
5
|
* getCostForEndpoint(endpoint) — sync, reads cache, returns { free, pro } or null
|
|
6
|
+
* getCostVariants(endpoint) — sync, reads cache, returns parameter-dependent costs or null
|
|
6
7
|
* refreshCostMapIfStale() — async, fetches inline if cache is missing or stale
|
|
7
8
|
*/
|
|
8
9
|
|
|
@@ -40,19 +41,42 @@ function writeAtomic(file, data) {
|
|
|
40
41
|
}
|
|
41
42
|
}
|
|
42
43
|
|
|
43
|
-
|
|
44
|
-
* Returns { free, pro } credit cost for the given API path, or null if unavailable.
|
|
45
|
-
*/
|
|
46
|
-
export function getCostForEndpoint(endpoint) {
|
|
44
|
+
function readCache() {
|
|
47
45
|
try {
|
|
48
46
|
if (!fs.existsSync(CACHE_FILE)) return null;
|
|
49
|
-
|
|
50
|
-
return costs?.[endpoint] ?? null;
|
|
47
|
+
return JSON.parse(fs.readFileSync(CACHE_FILE, 'utf8'));
|
|
51
48
|
} catch {
|
|
52
49
|
return null;
|
|
53
50
|
}
|
|
54
51
|
}
|
|
55
52
|
|
|
53
|
+
/**
|
|
54
|
+
* Returns { free, pro } credit cost for the given API path, or null if unavailable.
|
|
55
|
+
*/
|
|
56
|
+
export function getCostForEndpoint(endpoint) {
|
|
57
|
+
return readCache()?.costs?.[endpoint] ?? null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Returns the spec's x-credit-cost-variants for the given API path, e.g.
|
|
62
|
+
* { 'premium_labels=true': { pro: 150 }, ... }, or null if it has none.
|
|
63
|
+
*/
|
|
64
|
+
export function getCostVariants(endpoint) {
|
|
65
|
+
return readCache()?.variants?.[endpoint] ?? null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const credits = n => `${n} credit${n === 1 ? '' : 's'}`;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* "5 credits" when both tiers pay the same, otherwise both prices. A cost
|
|
72
|
+
* with no free price (premium labels) is Pro-only.
|
|
73
|
+
*/
|
|
74
|
+
export function formatCost({ free, pro }) {
|
|
75
|
+
if (free === pro) return credits(free);
|
|
76
|
+
if (free == null) return `${credits(pro)} (Pro tier only)`;
|
|
77
|
+
return `${credits(free)} (Free tier) / ${credits(pro)} (Pro tier)`;
|
|
78
|
+
}
|
|
79
|
+
|
|
56
80
|
/**
|
|
57
81
|
* What did (or would) this call cost?
|
|
58
82
|
*
|
|
@@ -105,17 +129,19 @@ export async function refreshCostMapIfStale() {
|
|
|
105
129
|
if (!spec?.paths || typeof spec.paths !== 'object') return;
|
|
106
130
|
|
|
107
131
|
const costs = {};
|
|
132
|
+
const variants = {};
|
|
108
133
|
for (const [p, methods] of Object.entries(spec.paths)) {
|
|
109
134
|
for (const op of Object.values(methods)) {
|
|
110
135
|
if (op['x-credit-cost']) {
|
|
111
136
|
costs[p] = op['x-credit-cost'];
|
|
137
|
+
if (op['x-credit-cost-variants']) variants[p] = op['x-credit-cost-variants'];
|
|
112
138
|
break;
|
|
113
139
|
}
|
|
114
140
|
}
|
|
115
141
|
}
|
|
116
142
|
|
|
117
143
|
if (!fs.existsSync(CONFIG_DIR)) fs.mkdirSync(CONFIG_DIR, { mode: 0o700, recursive: true });
|
|
118
|
-
writeAtomic(CACHE_FILE, JSON.stringify({ costs, fetchedAt: Date.now() }));
|
|
144
|
+
writeAtomic(CACHE_FILE, JSON.stringify({ costs, variants, fetchedAt: Date.now() }));
|
|
119
145
|
} catch {
|
|
120
146
|
// silent — network failure, parse error, write error
|
|
121
147
|
}
|