nansen-cli 1.46.0 → 2.0.1
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 +122 -0
- package/README.md +157 -14
- package/docs/browser-login.md +123 -0
- package/package.json +11 -2
- package/scripts/postinstall.js +35 -30
- package/skills/nansen-agent-guide/SKILL.md +13 -2
- package/skills/nansen-alerts-webhook-listener/SKILL.md +5 -2
- package/skills/nansen-dca-tracker/SKILL.md +10 -2
- package/skills/nansen-defi-positions/SKILL.md +5 -2
- package/skills/nansen-exit-signals/SKILL.md +10 -2
- package/skills/nansen-fund-tracker/SKILL.md +10 -2
- package/skills/nansen-general-search/SKILL.md +10 -2
- package/skills/nansen-holder-analysis/SKILL.md +10 -2
- package/skills/nansen-limit-orders/SKILL.md +6 -3
- package/skills/nansen-perp-screener/SKILL.md +10 -2
- package/skills/nansen-perp-trader-profile/SKILL.md +10 -2
- package/skills/nansen-polymarket-deep-dive/SKILL.md +10 -2
- package/skills/nansen-polymarket-insider-scan/SKILL.md +10 -2
- package/skills/nansen-polymarket-trader-profile/SKILL.md +10 -2
- package/skills/nansen-portfolio-tracker/SKILL.md +10 -2
- package/skills/nansen-prediction-markets/SKILL.md +10 -2
- package/skills/nansen-sm-cross-chain-flows/SKILL.md +10 -2
- package/skills/nansen-smart-alerts/SKILL.md +9 -4
- package/skills/nansen-smart-money-alpha/SKILL.md +10 -2
- package/skills/nansen-smart-money-tracker/SKILL.md +10 -2
- package/skills/nansen-smart-money-trend/SKILL.md +10 -2
- package/skills/nansen-token-research/SKILL.md +10 -2
- package/skills/nansen-token-screener/SKILL.md +14 -4
- package/skills/nansen-token-transfer-analysis/SKILL.md +10 -2
- package/skills/nansen-trading/SKILL.md +8 -2
- package/skills/nansen-wallet-batch/SKILL.md +10 -2
- package/skills/nansen-wallet-clustering/SKILL.md +10 -2
- package/skills/nansen-wallet-deep-dive/SKILL.md +10 -2
- package/skills/nansen-wallet-keychain-migration/SKILL.md +5 -2
- package/skills/nansen-wallet-manager/SKILL.md +11 -9
- package/skills/nansen-wallet-profiler/SKILL.md +10 -2
- package/skills/nansen-web-fetcher/SKILL.md +5 -2
- package/skills/nansen-web-searcher/SKILL.md +5 -2
- package/src/api.js +202 -104
- package/src/auth-browser.js +16 -0
- package/src/auth-credentials.js +73 -0
- package/src/auth-device.js +242 -0
- package/src/auth-key-input.js +46 -0
- package/src/auth-login.js +89 -0
- package/src/auth-state.js +487 -0
- package/src/auth-store-native.js +20 -0
- package/src/auth-store-worker.js +64 -0
- package/src/auth-store.js +140 -0
- package/src/auto-paginate.js +288 -0
- package/src/bridge.js +126 -21
- package/src/cache-inspect.js +345 -0
- package/src/cli.js +473 -199
- package/src/commands/agent.js +15 -7
- package/src/commands/completion.js +2 -15
- package/src/commands/mcp.js +20 -18
- package/src/cost-cache.js +16 -2
- package/src/debug.js +348 -0
- package/src/doctor.js +22 -45
- package/src/hl-action.js +41 -13
- package/src/limit-order.js +1 -1
- package/src/mcp-client-config.js +169 -0
- package/src/mcp-client-config.json +17 -0
- package/src/mcp-verify.js +6 -5
- package/src/perp.js +41 -0
- package/src/privy.js +12 -12
- package/src/response-meta.js +56 -1
- package/src/rpc-urls.js +9 -11
- package/src/schema.json +185 -8
- package/src/semver.js +23 -4
- package/src/swap-simulation.js +35 -30
- package/src/telemetry.js +20 -0
- package/src/trading.js +266 -29
- package/src/transfer.js +53 -6
- package/src/update-check.js +9 -1
- package/src/wallet.js +107 -17
- package/src/walletconnect-trading.js +24 -5
- package/src/x402-svm.js +123 -64
- package/src/x402.js +46 -14
package/src/cli.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
import { authConfigView } from './auth-credentials.js';
|
|
2
|
+
import { browserLogin, defaultAuthState, cleanupMessage } from './auth-login.js';
|
|
3
|
+
import { readApiKeyInput } from './auth-key-input.js';
|
|
1
4
|
/**
|
|
2
5
|
* Nansen CLI - Core logic (testable)
|
|
3
6
|
* Extracted from index.js for coverage
|
|
4
7
|
*/
|
|
5
8
|
|
|
6
|
-
import { NansenAPI, NansenError, CommandError, ErrorCode,
|
|
9
|
+
import { NansenAPI, NansenError, CommandError, ErrorCode, getConfigFile, validateAddress, normalizeAddress, sleep } from './api.js';
|
|
7
10
|
import { buildWalletCommands, WALLET_SUBCOMMANDS } from './wallet.js';
|
|
8
11
|
import { buildBridgeCommands, formatBridgeRoutes } from './bridge.js';
|
|
9
12
|
import { buildPerpCommands } from './perp.js';
|
|
@@ -15,6 +18,7 @@ import { buildMcpCommands } from './commands/mcp.js';
|
|
|
15
18
|
import { buildCompletionCommands } from './commands/completion.js';
|
|
16
19
|
import { buildResearchCommands, RESEARCH_HISTORICAL_SUBCOMMANDS, RESEARCH_SUBCOMMANDS } from './commands/research.js';
|
|
17
20
|
import { buildPagination, parseSort, parseCsvOption, rejectBlankOption, parseObjectOption } from './query-options.js';
|
|
21
|
+
import { enableAutoPagination, DEFAULT_MAX_PAGES, MAX_PAGES_LIMIT, locateRows } from './auto-paginate.js';
|
|
18
22
|
export { buildPagination, parseSort };
|
|
19
23
|
import { resolveAddress, isEnsName } from './ens.js';
|
|
20
24
|
import { compareSemver } from './semver.js';
|
|
@@ -22,8 +26,10 @@ import fs from 'fs';
|
|
|
22
26
|
import { getUpdateNotification, getUpgradeNotice, scheduleUpdateCheck } from './update-check.js';
|
|
23
27
|
import { getAuthStatus, runDoctorChecks, runConnectivityChecks, formatDoctorReport } from './doctor.js';
|
|
24
28
|
import { refreshCostMapIfStale, getCostForEndpoint, creditsCharged } from './cost-cache.js';
|
|
29
|
+
import { collectCacheStats, clearCaches, formatCacheStats, formatCacheClear } from './cache-inspect.js';
|
|
25
30
|
import { creditWarning, noticeWarnings } from './response-meta.js';
|
|
26
|
-
import { trackCommandSucceeded, trackCommandFailed } from './telemetry.js';
|
|
31
|
+
import { trackCommandSucceeded, trackCommandFailed, trackAuthCommand } from './telemetry.js';
|
|
32
|
+
import { setDebugEnabled } from './debug.js';
|
|
27
33
|
import { createRequire } from 'module';
|
|
28
34
|
import * as readline from 'readline';
|
|
29
35
|
|
|
@@ -179,6 +185,10 @@ export function compactSchema(schema) {
|
|
|
179
185
|
params_legend: '* = required',
|
|
180
186
|
commands,
|
|
181
187
|
globalOptions: Object.keys(schema.globalOptions).join(', '),
|
|
188
|
+
// Which commands cache, and how to control it. One rule rather than a flag
|
|
189
|
+
// repeated on every command — caching is a property of the request path,
|
|
190
|
+
// not of the individual command.
|
|
191
|
+
caching: schema.caching,
|
|
182
192
|
chains: schema.chains,
|
|
183
193
|
smartMoneyLabels: schema.smartMoneyLabels
|
|
184
194
|
};
|
|
@@ -189,10 +199,10 @@ export function compactSchema(schema) {
|
|
|
189
199
|
// subcommand, so it lives here rather than inline in parseArgs.
|
|
190
200
|
export const VALUELESS_FLAGS = new Set([
|
|
191
201
|
'pretty', 'help', 'version', 'table', 'no-retry', 'cache', 'no-cache', 'stream',
|
|
192
|
-
'enrich', 'full', 'human', 'enabled', 'disabled', 'expert', 'json', 'offline',
|
|
202
|
+
'enrich', 'full', 'human', 'no-browser', 'api-key-stdin', 'enabled', 'disabled', 'expert', 'json', 'offline',
|
|
193
203
|
'no-simulate', 'no-verify-outcome', 'no-revoke-excessive-allowance', 'dry-run',
|
|
194
204
|
'send-api-key', 'all', 'max', 'gasless', 'auto-slippage', 'unsafe-no-password',
|
|
195
|
-
'reveal', 'yes',
|
|
205
|
+
'reveal', 'yes', 'paginate', 'debug',
|
|
196
206
|
]);
|
|
197
207
|
|
|
198
208
|
export function parseArgs(args) {
|
|
@@ -370,6 +380,10 @@ function parseNonNegativeSafeIntegerOption(name, options, flags, defaultValue) {
|
|
|
370
380
|
'non-negative safe integer',
|
|
371
381
|
);
|
|
372
382
|
|
|
383
|
+
// Callers without an option or default intentionally receive undefined.
|
|
384
|
+
// Do not rely on JavaScript's `undefined < 0` coercion for that contract.
|
|
385
|
+
if (value === undefined) return undefined;
|
|
386
|
+
|
|
373
387
|
if (value < 0) {
|
|
374
388
|
throw new NansenError(
|
|
375
389
|
`--${name} must be a non-negative safe integer; received: ${value}`,
|
|
@@ -380,6 +394,36 @@ function parseNonNegativeSafeIntegerOption(name, options, flags, defaultValue) {
|
|
|
380
394
|
return value;
|
|
381
395
|
}
|
|
382
396
|
|
|
397
|
+
function parsePositiveSafeIntegerOption(name, options, flags, defaultValue, { max } = {}) {
|
|
398
|
+
const value = parseSafeIntegerOption(
|
|
399
|
+
name,
|
|
400
|
+
options,
|
|
401
|
+
flags,
|
|
402
|
+
defaultValue,
|
|
403
|
+
'positive safe integer',
|
|
404
|
+
);
|
|
405
|
+
|
|
406
|
+
// Keep the helper safe for future optional callers; the current pagination
|
|
407
|
+
// caller supplies DEFAULT_MAX_PAGES whenever this parser is activated.
|
|
408
|
+
if (value === undefined) return undefined;
|
|
409
|
+
|
|
410
|
+
if (value < 1) {
|
|
411
|
+
throw new NansenError(
|
|
412
|
+
`--${name} must be a positive safe integer; received: ${value}`,
|
|
413
|
+
ErrorCode.INVALID_PARAMS,
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
if (max !== undefined && value > max) {
|
|
418
|
+
throw new NansenError(
|
|
419
|
+
`--${name} must be at most ${max}; received: ${value}`,
|
|
420
|
+
ErrorCode.INVALID_PARAMS,
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
return value;
|
|
425
|
+
}
|
|
426
|
+
|
|
383
427
|
|
|
384
428
|
function parseDaysOption(options, flags) {
|
|
385
429
|
const days = parseNonNegativeSafeIntegerOption('days', options, flags, 30);
|
|
@@ -415,18 +459,11 @@ export function formatValue(val) {
|
|
|
415
459
|
// Table formatter for human-readable output
|
|
416
460
|
export function formatTable(data) {
|
|
417
461
|
// Extract array of records from various response shapes
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
} else if (data?.data && Array.isArray(data.data)) {
|
|
422
|
-
records = data.data;
|
|
423
|
-
} else if (data?.results && Array.isArray(data.results)) {
|
|
424
|
-
records = data.results;
|
|
425
|
-
} else if (data?.data?.results && Array.isArray(data.data.results)) {
|
|
426
|
-
records = data.data.results;
|
|
427
|
-
} else if (typeof data === 'object' && data !== null) {
|
|
462
|
+
const located = locateRows(data, { descriptive: true });
|
|
463
|
+
let records = located?.rows || [];
|
|
464
|
+
if (!located && typeof data === 'object' && data !== null) {
|
|
428
465
|
// Single object - convert to array
|
|
429
|
-
records = [data];
|
|
466
|
+
records = [Array.isArray(data) ? { data } : data];
|
|
430
467
|
}
|
|
431
468
|
|
|
432
469
|
if (records.length === 0) {
|
|
@@ -487,17 +524,10 @@ export function formatTable(data) {
|
|
|
487
524
|
*/
|
|
488
525
|
export function formatCsv(data) {
|
|
489
526
|
// Extract array of records from various response shapes
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
records = data.data;
|
|
495
|
-
} else if (data?.results && Array.isArray(data.results)) {
|
|
496
|
-
records = data.results;
|
|
497
|
-
} else if (data?.data?.results && Array.isArray(data.data.results)) {
|
|
498
|
-
records = data.data.results;
|
|
499
|
-
} else if (typeof data === 'object' && data !== null) {
|
|
500
|
-
records = [data];
|
|
527
|
+
const located = locateRows(data, { descriptive: true });
|
|
528
|
+
let records = located?.rows || [];
|
|
529
|
+
if (!located && typeof data === 'object' && data !== null) {
|
|
530
|
+
records = [Array.isArray(data) ? { data } : data];
|
|
501
531
|
}
|
|
502
532
|
|
|
503
533
|
if (records.length === 0) return '';
|
|
@@ -540,7 +570,7 @@ export function formatOutput(data, { pretty = false, table = false, csv = false
|
|
|
540
570
|
if (data.success === false) {
|
|
541
571
|
return { type: 'error', text: formatErrorText(data, { csv }) };
|
|
542
572
|
}
|
|
543
|
-
const body = data.data || data;
|
|
573
|
+
const body = Array.isArray(data.data) ? data : data.data || data;
|
|
544
574
|
return csv
|
|
545
575
|
? { type: 'csv', text: formatCsv(body) }
|
|
546
576
|
: { type: 'table', text: formatTable(body) };
|
|
@@ -592,17 +622,11 @@ export function formatError(error) {
|
|
|
592
622
|
* Each record is output as a separate JSON line
|
|
593
623
|
*/
|
|
594
624
|
export function formatStream(data) {
|
|
625
|
+
if (data?.success === false) return JSON.stringify(data);
|
|
595
626
|
// Extract array of records from various response shapes
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
} else if (data?.data && Array.isArray(data.data)) {
|
|
600
|
-
records = data.data;
|
|
601
|
-
} else if (data?.results && Array.isArray(data.results)) {
|
|
602
|
-
records = data.results;
|
|
603
|
-
} else if (data?.data?.results && Array.isArray(data.data.results)) {
|
|
604
|
-
records = data.data.results;
|
|
605
|
-
} else if (typeof data === 'object' && data !== null) {
|
|
627
|
+
const located = locateRows(data, { descriptive: true });
|
|
628
|
+
let records = located?.rows || [];
|
|
629
|
+
if (!located && typeof data === 'object' && data !== null) {
|
|
606
630
|
// Single object - output as single line
|
|
607
631
|
records = [data];
|
|
608
632
|
}
|
|
@@ -686,7 +710,11 @@ async function enrichTransfers(result, apiInstance, chain) {
|
|
|
686
710
|
const labelMap = {};
|
|
687
711
|
for (const addr of addrs) {
|
|
688
712
|
try {
|
|
689
|
-
const labelsResult = await apiInstance.addressLabels({
|
|
713
|
+
const labelsResult = await apiInstance.addressLabels({
|
|
714
|
+
address: addr,
|
|
715
|
+
chain,
|
|
716
|
+
requestOptions: { autoPaginate: false },
|
|
717
|
+
});
|
|
690
718
|
labelMap[addr] = Array.isArray(labelsResult?.data)
|
|
691
719
|
? labelsResult.data.map(item => item.label)
|
|
692
720
|
: labelsResult?.labels || [];
|
|
@@ -797,7 +825,11 @@ export async function batchProfile(api, params = {}) {
|
|
|
797
825
|
}
|
|
798
826
|
try {
|
|
799
827
|
if (include.includes('labels')) {
|
|
800
|
-
const labelsResult = await api.addressLabels({
|
|
828
|
+
const labelsResult = await api.addressLabels({
|
|
829
|
+
address,
|
|
830
|
+
chain,
|
|
831
|
+
requestOptions: { autoPaginate: false },
|
|
832
|
+
});
|
|
801
833
|
entry.labels = Array.isArray(labelsResult?.data)
|
|
802
834
|
? labelsResult.data
|
|
803
835
|
: labelsResult?.labels || [];
|
|
@@ -806,7 +838,11 @@ export async function batchProfile(api, params = {}) {
|
|
|
806
838
|
entry.balance = await api.addressBalance({ address, chain });
|
|
807
839
|
}
|
|
808
840
|
if (include.includes('pnl')) {
|
|
809
|
-
entry.pnl = await api.addressPnl({
|
|
841
|
+
entry.pnl = await api.addressPnl({
|
|
842
|
+
address,
|
|
843
|
+
chain,
|
|
844
|
+
requestOptions: { autoPaginate: false },
|
|
845
|
+
});
|
|
810
846
|
}
|
|
811
847
|
} catch (err) {
|
|
812
848
|
entry.error = err.message;
|
|
@@ -817,19 +853,37 @@ export async function batchProfile(api, params = {}) {
|
|
|
817
853
|
return { results, total: addresses.length, completed: results.filter(r => !r.error).length };
|
|
818
854
|
}
|
|
819
855
|
|
|
820
|
-
function normalizeTraceDepth(raw) {
|
|
856
|
+
function normalizeTraceDepth(raw, flags = {}) {
|
|
821
857
|
const value = parseSafeIntegerOption(
|
|
822
858
|
'depth',
|
|
823
859
|
{ depth: raw },
|
|
824
|
-
|
|
825
|
-
2,
|
|
860
|
+
flags,
|
|
826
861
|
);
|
|
827
862
|
|
|
828
863
|
return Math.max(1, Math.min(value, 5));
|
|
829
864
|
}
|
|
830
865
|
|
|
866
|
+
// --width is the fan-out at every hop, so it multiplies with --depth: an
|
|
867
|
+
// unbounded width on a hub-style address (exchange, router) turns one
|
|
868
|
+
// invocation into hundreds of counterparties calls and credits. Clamp it the
|
|
869
|
+
// way --depth is clamped, and stop expanding the graph past MAX_TRACE_NODES
|
|
870
|
+
// as a backstop for the depth × width product.
|
|
871
|
+
const MAX_TRACE_WIDTH = 50;
|
|
872
|
+
const MAX_TRACE_NODES = 1000;
|
|
873
|
+
|
|
874
|
+
function normalizeTraceWidth(raw) {
|
|
875
|
+
const value = parseNonNegativeSafeIntegerOption(
|
|
876
|
+
'width',
|
|
877
|
+
{ width: raw },
|
|
878
|
+
{},
|
|
879
|
+
10,
|
|
880
|
+
);
|
|
881
|
+
|
|
882
|
+
return Math.max(1, Math.min(value, MAX_TRACE_WIDTH));
|
|
883
|
+
}
|
|
884
|
+
|
|
831
885
|
export async function traceCounterparties(api, params = {}) {
|
|
832
|
-
let { address, chain = 'ethereum', depth = 2, width = 10, days = 30, delayMs = 1000 } = params;
|
|
886
|
+
let { address, chain = 'ethereum', depth = 2, depthFlags = {}, width = 10, days = 30, delayMs = 1000 } = params;
|
|
833
887
|
if (!address) {
|
|
834
888
|
throw new NansenError('address is required for trace', ErrorCode.MISSING_PARAM);
|
|
835
889
|
}
|
|
@@ -848,13 +902,15 @@ export async function traceCounterparties(api, params = {}) {
|
|
|
848
902
|
if (!validation.valid) {
|
|
849
903
|
throw new NansenError(validation.error, ErrorCode.INVALID_ADDRESS);
|
|
850
904
|
}
|
|
851
|
-
const clampedDepth = normalizeTraceDepth(depth);
|
|
905
|
+
const clampedDepth = normalizeTraceDepth(depth, depthFlags);
|
|
906
|
+
const clampedWidth = normalizeTraceWidth(width);
|
|
852
907
|
const visited = new Set();
|
|
853
908
|
const nodes = [];
|
|
854
909
|
const edges = [];
|
|
855
910
|
const queue = [{ addr: address, hop: 0 }];
|
|
856
911
|
visited.add(address);
|
|
857
912
|
nodes.push(address);
|
|
913
|
+
let truncated = false;
|
|
858
914
|
|
|
859
915
|
while (queue.length > 0) {
|
|
860
916
|
const { addr, hop } = queue.shift();
|
|
@@ -863,11 +919,12 @@ export async function traceCounterparties(api, params = {}) {
|
|
|
863
919
|
try {
|
|
864
920
|
const result = await api.addressCounterparties({
|
|
865
921
|
address: addr, chain, days,
|
|
866
|
-
pagination: { page: 1, per_page:
|
|
922
|
+
pagination: { page: 1, per_page: clampedWidth },
|
|
923
|
+
requestOptions: { autoPaginate: false },
|
|
867
924
|
});
|
|
868
925
|
|
|
869
926
|
const counterparties = result?.data?.results || result?.counterparties || result?.data || [];
|
|
870
|
-
const items = Array.isArray(counterparties) ? counterparties.slice(0,
|
|
927
|
+
const items = Array.isArray(counterparties) ? counterparties.slice(0, clampedWidth) : [];
|
|
871
928
|
|
|
872
929
|
for (const cp of items) {
|
|
873
930
|
const cpAddr = cp.counterparty_address || cp.address || cp.counterparty;
|
|
@@ -881,6 +938,11 @@ export async function traceCounterparties(api, params = {}) {
|
|
|
881
938
|
});
|
|
882
939
|
|
|
883
940
|
if (!visited.has(cpAddr)) {
|
|
941
|
+
if (nodes.length >= MAX_TRACE_NODES) {
|
|
942
|
+
// The edge is still recorded; the node is just not expanded.
|
|
943
|
+
truncated = true;
|
|
944
|
+
continue;
|
|
945
|
+
}
|
|
884
946
|
visited.add(cpAddr);
|
|
885
947
|
nodes.push(cpAddr);
|
|
886
948
|
queue.push({ addr: cpAddr, hop: hop + 1 });
|
|
@@ -894,9 +956,14 @@ export async function traceCounterparties(api, params = {}) {
|
|
|
894
956
|
}
|
|
895
957
|
|
|
896
958
|
return {
|
|
897
|
-
root: address, chain, depth: clampedDepth,
|
|
959
|
+
root: address, chain, depth: clampedDepth, width: clampedWidth,
|
|
898
960
|
nodes, edges,
|
|
899
|
-
stats: {
|
|
961
|
+
stats: {
|
|
962
|
+
nodes_visited: nodes.length,
|
|
963
|
+
edges_found: edges.length,
|
|
964
|
+
max_depth_reached: Math.max(0, ...edges.map(e => e.hop)),
|
|
965
|
+
truncated,
|
|
966
|
+
},
|
|
900
967
|
};
|
|
901
968
|
}
|
|
902
969
|
|
|
@@ -918,8 +985,12 @@ export async function compareWallets(api, params = {}) {
|
|
|
918
985
|
// error cannot masquerade as "no overlap" / "0 USD".
|
|
919
986
|
const settle = (promise) => promise.then(value => ({ value }), error => ({ error }));
|
|
920
987
|
const [cp1, cp2] = await Promise.all([
|
|
921
|
-
settle(api.addressCounterparties({
|
|
922
|
-
|
|
988
|
+
settle(api.addressCounterparties({
|
|
989
|
+
address: addr1, chain, days, requestOptions: { autoPaginate: false },
|
|
990
|
+
})),
|
|
991
|
+
settle(api.addressCounterparties({
|
|
992
|
+
address: addr2, chain, days, requestOptions: { autoPaginate: false },
|
|
993
|
+
})),
|
|
923
994
|
]);
|
|
924
995
|
await sleep(delayMs);
|
|
925
996
|
const [bal1, bal2] = await Promise.all([
|
|
@@ -1028,19 +1099,38 @@ COMMANDS:
|
|
|
1028
1099
|
alerts list, create, update, toggle, delete
|
|
1029
1100
|
web search, fetch
|
|
1030
1101
|
mcp install/uninstall/verify the Nansen MCP server
|
|
1031
|
-
account
|
|
1032
|
-
auth status — offline
|
|
1033
|
-
login
|
|
1034
|
-
logout Remove saved API
|
|
1102
|
+
account Check the effective credential, plan, and remaining credits (free)
|
|
1103
|
+
auth status — offline credential source and cached/unverified session metadata
|
|
1104
|
+
login Sign in through browser approval (--no-browser for remote terminals)
|
|
1105
|
+
logout Remove saved API authentication; preserve wallets
|
|
1035
1106
|
doctor Diagnostics: auth, wallets, caches, connectivity (--offline --json)
|
|
1036
1107
|
schema JSON schema for all commands (use "nansen schema <cmd>" for one)
|
|
1037
1108
|
completion Shell completions: bash, zsh, fish
|
|
1038
|
-
cache clear
|
|
1109
|
+
cache stats, clear
|
|
1039
1110
|
changelog --since <version> to filter
|
|
1040
1111
|
|
|
1041
|
-
OPTIONS: --chain --limit --sort field:dir --fields a,b --days N --filters '{}'
|
|
1112
|
+
OPTIONS: --chain --limit --page N --sort field:dir --fields a,b --days N --filters '{}'
|
|
1113
|
+
PAGING: --paginate (alias --all) fetch every page, --max-pages N (default 10), --limit sets page size
|
|
1042
1114
|
FORMAT: --pretty --table --format csv --stream (NDJSON)
|
|
1043
1115
|
RETRY: --no-retry --retries N --cache --cache-ttl N
|
|
1116
|
+
DEBUG: --debug (or NANSEN_DEBUG=1) traces each request on stderr: method, URL,
|
|
1117
|
+
status, time-to-headers (TTFB), retries, request id. Never prints
|
|
1118
|
+
credentials or bodies.
|
|
1119
|
+
|
|
1120
|
+
AUTHENTICATION:
|
|
1121
|
+
nansen login Fresh browser approval, even with an existing key/session
|
|
1122
|
+
nansen login --no-browser Same approval without opening the browser
|
|
1123
|
+
nansen auth status Offline, cached/unverified; does not open session storage
|
|
1124
|
+
nansen account Free live check of the effective credential
|
|
1125
|
+
nansen login --human Explicit legacy key setup; also persists an injected env key
|
|
1126
|
+
nansen login --api-key-stdin Read a key from a pipe or file; never echo the key
|
|
1127
|
+
NANSEN_API_KEY overrides saved authentication.
|
|
1128
|
+
API keys and browser sessions can auto-pay supported HTTP 402 challenges under the same wallet controls and spending limits.
|
|
1129
|
+
Authentication failures never trigger payment; login verification and nansen account never auto-pay.
|
|
1130
|
+
Browser sessions renew automatically; uncertain renewal requires fresh login.
|
|
1131
|
+
Browser nansen:api sessions have API-key-equivalent account permissions; wallet signing is separate.
|
|
1132
|
+
Browser login is enabled in production; saved sessions need native storage (see docs/browser-login.md).
|
|
1133
|
+
Public API endpoints keep their usual account, plan and credit checks; MCP key export is separate.
|
|
1044
1134
|
|
|
1045
1135
|
TRADING:
|
|
1046
1136
|
nansen trade quote --chain solana --from SOL --to USDC --amount 1000000000
|
|
@@ -1077,6 +1167,46 @@ Skills: npx skills add nansen-ai/nansen-cli (agent-optimised docs per command gr
|
|
|
1077
1167
|
Telemetry: anonymous usage stats (commands, timing, errors). Perp order/close additionally send each leg's side, outcome, order id, shared submission id, and a SHA-256 wallet identifier. Raw wallet, price, size, and exchange error text are not sent. Disable: DO_NOT_TRACK=1
|
|
1078
1168
|
`;
|
|
1079
1169
|
|
|
1170
|
+
// Usage text for the `cache` command group. Also the answer to "which commands
|
|
1171
|
+
// cache?" — caching is decided by the request path, so the rule lives here (and
|
|
1172
|
+
// in schema.json under `caching`) rather than being repeated per command.
|
|
1173
|
+
export const CACHE_HELP = `nansen cache — inspect and clear the caches this CLI keeps on disk
|
|
1174
|
+
|
|
1175
|
+
SUBCOMMANDS:
|
|
1176
|
+
stats [--json] What each cache holds: entries, size, age, effective TTL
|
|
1177
|
+
clear [target] Delete cached entries (default target: responses)
|
|
1178
|
+
|
|
1179
|
+
CLEAR TARGETS:
|
|
1180
|
+
responses API responses saved when --cache is passed (default)
|
|
1181
|
+
cost-map Per-endpoint credit costs, refreshed every 24h
|
|
1182
|
+
update-check Latest published version, refreshed every 24h
|
|
1183
|
+
all All three
|
|
1184
|
+
|
|
1185
|
+
WHAT CACHES:
|
|
1186
|
+
Caching is off by default and opt-in per invocation with --cache. With it on,
|
|
1187
|
+
every read the CLI makes through the Nansen API client is served from and
|
|
1188
|
+
written to the response cache — that is all of "nansen research ...", plus
|
|
1189
|
+
"alerts list" and "alerts get".
|
|
1190
|
+
Never cached: account, web search, web fetch, alerts create/update/toggle/delete,
|
|
1191
|
+
agent (streamed), every trade, bridge, wallet and mcp command, and perp trading.
|
|
1192
|
+
The analytics commands "perp screener" and "perp leaderboard" are cached.
|
|
1193
|
+
|
|
1194
|
+
CACHE OPTIONS (for any command):
|
|
1195
|
+
--cache Enable caching for this invocation
|
|
1196
|
+
--no-cache Bypass the cache for this invocation (or NANSEN_NO_CACHE=1)
|
|
1197
|
+
--cache-ttl <seconds> Non-negative safe integer TTL (default: 300; 0 disables reads)
|
|
1198
|
+
|
|
1199
|
+
EXAMPLES:
|
|
1200
|
+
nansen cache stats
|
|
1201
|
+
nansen cache stats --json --pretty
|
|
1202
|
+
nansen cache clear
|
|
1203
|
+
nansen cache clear all
|
|
1204
|
+
|
|
1205
|
+
Saved trade quotes are not a cache and are never touched by "cache clear": they
|
|
1206
|
+
expire on their own, and an unexecuted quote is still spendable. Credentials,
|
|
1207
|
+
wallets and config are never changed by this command. CLI startup loads the saved
|
|
1208
|
+
config as usual.`;
|
|
1209
|
+
|
|
1080
1210
|
// Usage text for the `trade` command group. Shared by the trade handler and the
|
|
1081
1211
|
// --help path in runCLI, so `nansen trade`, `nansen trade <sub> --help`, and the
|
|
1082
1212
|
// deprecated top-level `quote`/`execute --help` all show the same usage.
|
|
@@ -1204,6 +1334,46 @@ export async function promptForConfirmation(question, { input = process.stdin, o
|
|
|
1204
1334
|
});
|
|
1205
1335
|
}
|
|
1206
1336
|
|
|
1337
|
+
// `token screener --search` filters client-side, so it can only find a token
|
|
1338
|
+
// among the candidate rows the API returned. These helpers describe that window
|
|
1339
|
+
// as `_meta.search: { query, searched, matched, complete }` so a short or empty
|
|
1340
|
+
// result can be told apart from "the token ranks below the rows we fetched".
|
|
1341
|
+
function locatePaginationSummary(result) {
|
|
1342
|
+
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
1343
|
+
if (isObject(result?.pagination)) return result.pagination;
|
|
1344
|
+
if (isObject(result?.data?.pagination)) return result.data.pagination;
|
|
1345
|
+
return null;
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
function describeSearchWindow({ query, candidates, matched, perPage, summary }) {
|
|
1349
|
+
let complete;
|
|
1350
|
+
if (typeof summary?.complete === 'boolean') {
|
|
1351
|
+
// --paginate traversal summary (auto-paginate.js): false when --max-pages
|
|
1352
|
+
// stopped the walk before the server ran out of rows. It also carries the
|
|
1353
|
+
// first page's stale is_last_page, so it has to be checked first.
|
|
1354
|
+
complete = summary.complete;
|
|
1355
|
+
} else if (typeof summary?.is_last_page === 'boolean') {
|
|
1356
|
+
// Server metadata on the single candidate page.
|
|
1357
|
+
complete = summary.is_last_page;
|
|
1358
|
+
} else {
|
|
1359
|
+
// No metadata: a full page means the API may hold more rows beyond it.
|
|
1360
|
+
complete = candidates.length < perPage;
|
|
1361
|
+
}
|
|
1362
|
+
return { query, searched: candidates.length, matched, complete };
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
function searchWindowNote(searchMeta, summary, paginateAll) {
|
|
1366
|
+
const rows = `${searchMeta.searched} screener row${searchMeta.searched === 1 ? '' : 's'}`;
|
|
1367
|
+
if (paginateAll) {
|
|
1368
|
+
const pages = Number.isInteger(summary?.pages_fetched)
|
|
1369
|
+
? ` after ${summary.pages_fetched} candidate page${summary.pages_fetched === 1 ? '' : 's'} (--max-pages)`
|
|
1370
|
+
: '';
|
|
1371
|
+
const resume = Number.isInteger(summary?.next_page) ? ` or resume with --page ${summary.next_page}` : '';
|
|
1372
|
+
return `Note: --search stopped${pages} with ${rows} checked; tokens beyond them were not searched (_meta.search.complete: false). Raise --max-pages${resume}.`;
|
|
1373
|
+
}
|
|
1374
|
+
return `Note: --search matched against only the first ${rows}; tokens ranked below them were not searched (_meta.search.complete: false). Widen the window with --limit <n> (max 1000) or --paginate, or narrow the candidates with --filters.`;
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1207
1377
|
// Build command handlers (returns object with handler functions)
|
|
1208
1378
|
export function buildCommands(deps = {}) {
|
|
1209
1379
|
// Allow dependency injection for testing
|
|
@@ -1215,12 +1385,14 @@ export function buildCommands(deps = {}) {
|
|
|
1215
1385
|
promptFn = prompt,
|
|
1216
1386
|
confirmationPromptFn,
|
|
1217
1387
|
log = console.log,
|
|
1218
|
-
errorOutput
|
|
1388
|
+
errorOutput = console.error,
|
|
1219
1389
|
NansenAPIClass: _NansenAPIClass = NansenAPI,
|
|
1220
|
-
|
|
1221
|
-
|
|
1390
|
+
authState = defaultAuthState(),
|
|
1391
|
+
browserLoginFn = browserLogin,
|
|
1222
1392
|
getConfigFileFn = getConfigFile,
|
|
1223
|
-
|
|
1393
|
+
stdoutTTY = deps.isTTY ?? process.stdout.isTTY,
|
|
1394
|
+
stdinTTY = deps.isTTY ?? process.stdin.isTTY,
|
|
1395
|
+
stdin = process.stdin,
|
|
1224
1396
|
env = process.env
|
|
1225
1397
|
} = deps;
|
|
1226
1398
|
|
|
@@ -1333,29 +1505,28 @@ export function buildCommands(deps = {}) {
|
|
|
1333
1505
|
},
|
|
1334
1506
|
|
|
1335
1507
|
'login': async (args, apiInstance, flags, options) => {
|
|
1336
|
-
if (
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
log(' nansen login (uses NANSEN_API_KEY when already set)');
|
|
1341
|
-
log(' nansen login --api-key <key> (literal key IS recorded in shell history)\n');
|
|
1342
|
-
log('OPTIONS:');
|
|
1343
|
-
log(' --api-key <key> Your Nansen API key (recorded in shell history — prefer --human)');
|
|
1344
|
-
log(' --human Enable interactive prompt');
|
|
1345
|
-
log(' --help Show this help\n');
|
|
1346
|
-
log('Setting a literal key in a command may record it in shell history.');
|
|
1347
|
-
log('Get your API key at: https://app.nansen.ai/auth/agent-setup');
|
|
1348
|
-
return;
|
|
1508
|
+
if ('api-key-stdin' in options) throw new CommandError('--api-key-stdin does not accept a value.', 'INVALID_PARAMS');
|
|
1509
|
+
const fromStdin = flags['api-key-stdin'] === true;
|
|
1510
|
+
if (fromStdin && (args.length || flags.human || flags['no-browser'] || flags['api-key'] || 'api-key' in options)) {
|
|
1511
|
+
throw new CommandError('--api-key-stdin cannot be combined with arguments, --api-key, --human, or --no-browser.', 'INVALID_PARAMS');
|
|
1349
1512
|
}
|
|
1513
|
+
if (flags['api-key']) throw new CommandError('--api-key requires a value.', 'MISSING_PARAM');
|
|
1514
|
+
if ('api-key' in options && typeof options['api-key'] !== 'string') throw new CommandError('--api-key must be a single key string.', 'INVALID_PARAMS');
|
|
1515
|
+
if (!fromStdin && !flags.human && options['api-key'] === undefined) {
|
|
1516
|
+
if (!stdinTTY || !stdoutTTY) {
|
|
1517
|
+
throw new CommandError('Browser login requires an interactive terminal. In a headless environment, set NANSEN_API_KEY and run nansen login --human, or pipe a key to nansen login --api-key-stdin.', 'NOT_A_TTY');
|
|
1518
|
+
}
|
|
1519
|
+
return browserLoginFn({ flags, env, isTTY: stdoutTTY, log, errorOutput, state: authState });
|
|
1520
|
+
}
|
|
1521
|
+
if (flags['no-browser']) throw new CommandError('--no-browser cannot be combined with legacy key setup.', 'INVALID_PARAMS');
|
|
1522
|
+
let apiKey = fromStdin ? await readApiKeyInput(stdin, stdinTTY) : options['api-key'];
|
|
1350
1523
|
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
if (!apiKey) {
|
|
1354
|
-
apiKey = process.env.NANSEN_API_KEY;
|
|
1524
|
+
if (apiKey === undefined) {
|
|
1525
|
+
apiKey = env.NANSEN_API_KEY?.trim() || undefined;
|
|
1355
1526
|
}
|
|
1356
1527
|
|
|
1357
|
-
if (
|
|
1358
|
-
if (!
|
|
1528
|
+
if (apiKey === undefined && flags.human) {
|
|
1529
|
+
if (!stdinTTY) {
|
|
1359
1530
|
throw new CommandError('--human requires an interactive terminal. Set NANSEN_API_KEY in the environment (or pass --api-key <key>, which is recorded in shell history).', 'NOT_A_TTY', {
|
|
1360
1531
|
error: 'NOT_A_TTY',
|
|
1361
1532
|
message: '--human requires an interactive terminal. Set NANSEN_API_KEY in the environment (or pass --api-key <key>, which is recorded in shell history).',
|
|
@@ -1378,57 +1549,70 @@ export function buildCommands(deps = {}) {
|
|
|
1378
1549
|
});
|
|
1379
1550
|
}
|
|
1380
1551
|
|
|
1381
|
-
// Verify API key before saving
|
|
1382
|
-
const NansenAPIClass = _NansenAPIClass;
|
|
1383
|
-
const testApi = new NansenAPIClass(apiKey.trim(), undefined, {
|
|
1384
|
-
retry: { maxRetries: 2 },
|
|
1385
|
-
cache: { enabled: false }
|
|
1386
|
-
});
|
|
1387
|
-
|
|
1388
1552
|
let accountInfo;
|
|
1553
|
+
let cleanup;
|
|
1554
|
+
const baseUrl = authConfigView(env).baseUrl;
|
|
1555
|
+
const attempt = await authState.begin({ preflight: false });
|
|
1389
1556
|
try {
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1557
|
+
// Verify API key before saving
|
|
1558
|
+
const NansenAPIClass = _NansenAPIClass;
|
|
1559
|
+
const testApi = new NansenAPIClass(apiKey.trim(), baseUrl, {
|
|
1560
|
+
allowPayment: false,
|
|
1561
|
+
redactAuthDiagnostics: fromStdin,
|
|
1562
|
+
retry: { maxRetries: 2 },
|
|
1563
|
+
cache: { enabled: false }
|
|
1564
|
+
});
|
|
1565
|
+
|
|
1566
|
+
try {
|
|
1567
|
+
accountInfo = await testApi.getAccount();
|
|
1568
|
+
} catch (error) {
|
|
1569
|
+
if (error.code === ErrorCode.UNAUTHORIZED) {
|
|
1570
|
+
throw new CommandError('The API key is not valid.', 'INVALID_API_KEY', {
|
|
1571
|
+
error: 'INVALID_API_KEY',
|
|
1572
|
+
message: 'The API key is not valid.',
|
|
1573
|
+
resolution: ['Check or rotate your key at https://app.nansen.ai/api?tab=api'],
|
|
1574
|
+
});
|
|
1575
|
+
}
|
|
1576
|
+
// Restore signal from the STRUCTURED error code only — never from
|
|
1577
|
+
// error.message, which can echo the upstream response body (and the key
|
|
1578
|
+
// with it). A transient failure shouldn't read as "check your key".
|
|
1579
|
+
let message = 'Could not verify API key.';
|
|
1580
|
+
let resolution = ['Check your internet connection', 'Try again'];
|
|
1581
|
+
if (error.code === ErrorCode.RATE_LIMITED) {
|
|
1582
|
+
message = 'Rate limited while verifying the API key.';
|
|
1583
|
+
resolution = ['Wait a moment, then retry explicit key setup: nansen login --human'];
|
|
1584
|
+
} else if (error.code === ErrorCode.SERVER_ERROR || error.code === ErrorCode.SERVICE_UNAVAILABLE) {
|
|
1585
|
+
message = 'The Nansen API is unavailable right now, so the key could not be verified.';
|
|
1586
|
+
resolution = ['Try again shortly'];
|
|
1587
|
+
} else if (error.code === ErrorCode.TIMEOUT) {
|
|
1588
|
+
message = 'Timed out verifying the API key.';
|
|
1589
|
+
resolution = ['Check your connection', 'Try again'];
|
|
1590
|
+
}
|
|
1591
|
+
throw new CommandError(message, 'VERIFICATION_FAILED', {
|
|
1592
|
+
error: 'VERIFICATION_FAILED',
|
|
1593
|
+
message,
|
|
1594
|
+
resolution,
|
|
1397
1595
|
});
|
|
1398
1596
|
}
|
|
1399
|
-
// Restore signal from the STRUCTURED error code only — never from
|
|
1400
|
-
// error.message, which can echo the upstream response body (and the key
|
|
1401
|
-
// with it). A transient failure shouldn't read as "check your key".
|
|
1402
|
-
let message = 'Could not verify API key.';
|
|
1403
|
-
let resolution = ['Check your internet connection', 'Try again'];
|
|
1404
|
-
if (error.code === ErrorCode.RATE_LIMITED) {
|
|
1405
|
-
message = 'Rate limited while verifying the API key.';
|
|
1406
|
-
resolution = ['Wait a moment, then run nansen login again'];
|
|
1407
|
-
} else if (error.code === ErrorCode.SERVER_ERROR || error.code === ErrorCode.SERVICE_UNAVAILABLE) {
|
|
1408
|
-
message = 'The Nansen API is unavailable right now, so the key could not be verified.';
|
|
1409
|
-
resolution = ['Try again shortly'];
|
|
1410
|
-
} else if (error.code === ErrorCode.TIMEOUT) {
|
|
1411
|
-
message = 'Timed out verifying the API key.';
|
|
1412
|
-
resolution = ['Check your connection', 'Try again'];
|
|
1413
|
-
}
|
|
1414
|
-
throw new CommandError(message, 'VERIFICATION_FAILED', {
|
|
1415
|
-
error: 'VERIFICATION_FAILED',
|
|
1416
|
-
message,
|
|
1417
|
-
resolution,
|
|
1418
|
-
});
|
|
1419
|
-
}
|
|
1420
1597
|
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1598
|
+
const result = await authState.install(attempt, { apiKey: apiKey.trim(), baseUrl });
|
|
1599
|
+
cleanup = result.cleanup;
|
|
1600
|
+
if (!fromStdin || !flags.json) for (const message of cleanupMessage(cleanup)) log(message);
|
|
1601
|
+
} finally { await authState.finish(attempt); }
|
|
1602
|
+
const blankEnvKey = env.NANSEN_API_KEY !== undefined && !env.NANSEN_API_KEY.trim();
|
|
1603
|
+
if (fromStdin && flags.json) {
|
|
1604
|
+
log(JSON.stringify({ event: 'saved', effective_source: blankEnvKey || env.NANSEN_API_KEY === undefined ? 'config' : 'env', environment_key_blank: blankEnvKey, cleanup }));
|
|
1605
|
+
return;
|
|
1606
|
+
}
|
|
1607
|
+
if (env.NANSEN_API_KEY?.trim()) log('Commands still use NANSEN_API_KEY. Unset it to use the saved credential.');
|
|
1426
1608
|
|
|
1427
1609
|
log(`✓ Saved to ${getConfigFileFn()}\n`);
|
|
1428
|
-
|
|
1610
|
+
// Verification responses may reflect the submitted key. Stdin login
|
|
1611
|
+
// prints only local status, including when upstream fields look harmless.
|
|
1612
|
+
if (!fromStdin && accountInfo?.plan) {
|
|
1429
1613
|
log(`Plan: ${accountInfo.plan}`);
|
|
1430
1614
|
}
|
|
1431
|
-
if (accountInfo?.credits_remaining !== undefined) {
|
|
1615
|
+
if (!fromStdin && accountInfo?.credits_remaining !== undefined) {
|
|
1432
1616
|
log(`Credits remaining: ${accountInfo.credits_remaining}`);
|
|
1433
1617
|
}
|
|
1434
1618
|
log('\nYou can now use the Nansen CLI. Try:');
|
|
@@ -1436,15 +1620,11 @@ export function buildCommands(deps = {}) {
|
|
|
1436
1620
|
},
|
|
1437
1621
|
|
|
1438
1622
|
'logout': async (_args, _apiInstance, _flags, _options) => {
|
|
1439
|
-
const
|
|
1440
|
-
if (
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
}
|
|
1445
|
-
if (env.NANSEN_API_KEY) {
|
|
1446
|
-
log('Warning: NANSEN_API_KEY remains active. Run: unset NANSEN_API_KEY');
|
|
1447
|
-
}
|
|
1623
|
+
const result = await authState.logout();
|
|
1624
|
+
if (result.cleanup.some(item => item.local === 'incomplete')) log('Saved authentication selection cleared; secure-store deletion incomplete.');
|
|
1625
|
+
else log(result.removed ? 'Local credentials removed.' : 'No saved credentials found.');
|
|
1626
|
+
for (const message of cleanupMessage(result.cleanup)) log(message);
|
|
1627
|
+
if (env.NANSEN_API_KEY?.trim()) log('Warning: NANSEN_API_KEY remains active. Run: unset NANSEN_API_KEY');
|
|
1448
1628
|
},
|
|
1449
1629
|
|
|
1450
1630
|
'help': async (_args, _apiInstance, _flags, _options) => {
|
|
@@ -1522,32 +1702,44 @@ export function buildCommands(deps = {}) {
|
|
|
1522
1702
|
return compactSchema(SCHEMA);
|
|
1523
1703
|
},
|
|
1524
1704
|
|
|
1525
|
-
'cache': async (args, _apiInstance,
|
|
1526
|
-
const subcommand = args[0]
|
|
1527
|
-
|
|
1705
|
+
'cache': async (args, _apiInstance, flags, options) => {
|
|
1706
|
+
const subcommand = args[0] ?? 'help';
|
|
1707
|
+
|
|
1528
1708
|
const handlers = {
|
|
1709
|
+
'stats': () => {
|
|
1710
|
+
// The TTL this invocation would apply, so "expired" means what the
|
|
1711
|
+
// next call would actually discard.
|
|
1712
|
+
const responseTtlSeconds = parseNonNegativeSafeIntegerOption('cache-ttl', options, flags, 300);
|
|
1713
|
+
const stats = collectCacheStats({ responseTtlSeconds });
|
|
1714
|
+
if (flags.json) return stats;
|
|
1715
|
+
log(formatCacheStats(stats));
|
|
1716
|
+
},
|
|
1529
1717
|
'clear': () => {
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1718
|
+
// Deleting local state needs an explicit target. The default is the
|
|
1719
|
+
// response cache alone — the one cache that is always safely
|
|
1720
|
+
// refetchable — and wiping everything requires saying "all".
|
|
1721
|
+
const target = args[1] ?? 'responses';
|
|
1722
|
+
log(formatCacheClear(clearCaches(target)));
|
|
1533
1723
|
},
|
|
1534
1724
|
'help': () => {
|
|
1535
|
-
log(
|
|
1536
|
-
log('USAGE:');
|
|
1537
|
-
log(' nansen cache clear Clear all cached responses\n');
|
|
1538
|
-
log('CACHE OPTIONS (for any command):');
|
|
1539
|
-
log(' --cache Enable caching for this session');
|
|
1540
|
-
log(' --no-cache Bypass cache for this request');
|
|
1541
|
-
log(' --cache-ttl <seconds> Set non-negative safe integer cache TTL (default: 300)');
|
|
1725
|
+
log(CACHE_HELP);
|
|
1542
1726
|
}
|
|
1543
1727
|
};
|
|
1544
|
-
|
|
1545
|
-
if (!handlers
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1728
|
+
|
|
1729
|
+
if (!Object.hasOwn(handlers, subcommand)) {
|
|
1730
|
+
throw new NansenError(
|
|
1731
|
+
`Unknown cache subcommand: ${subcommand}. Use one of: stats, clear`,
|
|
1732
|
+
ErrorCode.INVALID_PARAMS,
|
|
1733
|
+
);
|
|
1734
|
+
}
|
|
1735
|
+
|
|
1736
|
+
const maxArgs = subcommand === 'clear' ? 2 : 1;
|
|
1737
|
+
if (args.length > maxArgs) {
|
|
1738
|
+
throw new NansenError(
|
|
1739
|
+
`Too many cache arguments. Use: nansen cache ${subcommand}${subcommand === 'clear' ? ' [responses|cost-map|update-check|all]' : ''}`,
|
|
1740
|
+
ErrorCode.INVALID_PARAMS,
|
|
1741
|
+
);
|
|
1549
1742
|
}
|
|
1550
|
-
|
|
1551
1743
|
return handlers[subcommand]();
|
|
1552
1744
|
},
|
|
1553
1745
|
|
|
@@ -1680,16 +1872,10 @@ export function buildCommands(deps = {}) {
|
|
|
1680
1872
|
'trace': () => {
|
|
1681
1873
|
rejectBlankOption(options.delay, 'delay', '1000');
|
|
1682
1874
|
rejectBlankOption(options.depth, 'depth', '2');
|
|
1683
|
-
|
|
1684
|
-
throw new NansenError(
|
|
1685
|
-
'--depth requires a safe integer value',
|
|
1686
|
-
ErrorCode.INVALID_PARAMS,
|
|
1687
|
-
);
|
|
1688
|
-
}
|
|
1689
|
-
const depth = options.depth ?? 2;
|
|
1875
|
+
const depth = options.depth;
|
|
1690
1876
|
const width = parseNonNegativeSafeIntegerOption('width', options, flags, 10);
|
|
1691
1877
|
const delayMs = parseNonNegativeSafeIntegerOption('delay', options, flags, 1000);
|
|
1692
|
-
return traceCounterparties(apiInstance, { address, chain, depth, width, days, delayMs });
|
|
1878
|
+
return traceCounterparties(apiInstance, { address, chain, depth, depthFlags: flags, width, days, delayMs });
|
|
1693
1879
|
},
|
|
1694
1880
|
'compare': () => {
|
|
1695
1881
|
const addrs = parseAddressList(options.addresses);
|
|
@@ -1767,24 +1953,57 @@ export function buildCommands(deps = {}) {
|
|
|
1767
1953
|
// candidate fetch has to cover every page up to the requested one.
|
|
1768
1954
|
const requestedLimit = pagination?.per_page || 100;
|
|
1769
1955
|
const requestedPage = pagination?.page || 1;
|
|
1956
|
+
const paginateAll = flags.paginate || flags.all;
|
|
1770
1957
|
const searchPagination = search
|
|
1771
|
-
? {
|
|
1958
|
+
? {
|
|
1959
|
+
page: paginateAll ? requestedPage : 1,
|
|
1960
|
+
// A normal client-side search widens its one candidate fetch.
|
|
1961
|
+
// With --paginate, keep --limit as the server page size: the
|
|
1962
|
+
// traversal already fetches up to --max-pages separately
|
|
1963
|
+
// billed pages, so silently multiplying each one to 500 would
|
|
1964
|
+
// make the flag much more expensive than documented.
|
|
1965
|
+
per_page: paginateAll
|
|
1966
|
+
? requestedLimit
|
|
1967
|
+
: Math.max(500, requestedPage * requestedLimit),
|
|
1968
|
+
}
|
|
1772
1969
|
: pagination;
|
|
1773
1970
|
const result = await apiInstance.tokenScreener({ chains, timeframe, filters, orderBy, pagination: searchPagination });
|
|
1774
1971
|
if (search) {
|
|
1775
1972
|
const q = search.toLowerCase();
|
|
1776
1973
|
const offset = (requestedPage - 1) * requestedLimit;
|
|
1777
|
-
const filterArr = (arr) => arr.filter(t =>
|
|
1778
|
-
(t.token_symbol && t.token_symbol.toLowerCase().includes(q)) ||
|
|
1779
|
-
(t.token_name && t.token_name.toLowerCase().includes(q)) ||
|
|
1780
|
-
(t.token_address && t.token_address.toLowerCase() === q)
|
|
1781
|
-
).slice(offset, offset + requestedLimit);
|
|
1782
1974
|
// Handle nested response shapes: {data: [...]} or {data: {data: [...]}}
|
|
1975
|
+
let candidates;
|
|
1976
|
+
let rebuild;
|
|
1783
1977
|
if (Array.isArray(result?.data)) {
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1978
|
+
candidates = result.data;
|
|
1979
|
+
rebuild = rows => ({ ...result, data: rows });
|
|
1980
|
+
} else if (Array.isArray(result?.data?.data)) {
|
|
1981
|
+
candidates = result.data.data;
|
|
1982
|
+
rebuild = rows => ({ ...result, data: { ...result.data, data: rows } });
|
|
1983
|
+
} else {
|
|
1984
|
+
return result;
|
|
1787
1985
|
}
|
|
1986
|
+
const matching = candidates.filter(t =>
|
|
1987
|
+
(t.token_symbol && t.token_symbol.toLowerCase().includes(q)) ||
|
|
1988
|
+
(t.token_name && t.token_name.toLowerCase().includes(q)) ||
|
|
1989
|
+
(t.token_address && t.token_address.toLowerCase() === q)
|
|
1990
|
+
);
|
|
1991
|
+
// Filtering only replaces the row array. With --paginate, the
|
|
1992
|
+
// preserved pagination metadata describes candidate traversal,
|
|
1993
|
+
// not the number of client-side matches.
|
|
1994
|
+
const filtered = rebuild(paginateAll ? matching : matching.slice(offset, offset + requestedLimit));
|
|
1995
|
+
// The search only saw the candidates fetched above, so say how far it
|
|
1996
|
+
// looked: `complete: false` means the API had more rows past the
|
|
1997
|
+
// window and a token that is missing here may simply rank below it.
|
|
1998
|
+
const summary = locatePaginationSummary(result);
|
|
1999
|
+
const searchMeta = describeSearchWindow({
|
|
2000
|
+
query: search, candidates, matched: matching.length, perPage: searchPagination.per_page, summary,
|
|
2001
|
+
});
|
|
2002
|
+
filtered._meta = { ...(result._meta || {}), search: searchMeta };
|
|
2003
|
+
// stderr, so --fields/--table/--csv/--stream callers that never see
|
|
2004
|
+
// _meta still learn the search was cut short.
|
|
2005
|
+
if (!searchMeta.complete) errorOutput(searchWindowNote(searchMeta, summary, paginateAll));
|
|
2006
|
+
return filtered;
|
|
1788
2007
|
}
|
|
1789
2008
|
return result;
|
|
1790
2009
|
},
|
|
@@ -1867,7 +2086,17 @@ export function buildCommands(deps = {}) {
|
|
|
1867
2086
|
|
|
1868
2087
|
// Enrich transfers with Nansen labels for from/to addresses
|
|
1869
2088
|
if (subcommand === 'transfers' && (options.enrich || flags.enrich)) {
|
|
1870
|
-
|
|
2089
|
+
// Label lookups are auxiliary requests and may themselves carry a
|
|
2090
|
+
// pagination body. Preserve the primary transfer traversal metadata
|
|
2091
|
+
// that runCLI reports after the command completes.
|
|
2092
|
+
const transferPaginationMeta = apiInstance.paginatedResponseMeta;
|
|
2093
|
+
const transferPaginationEndpoint = apiInstance.paginatedEndpoint;
|
|
2094
|
+
try {
|
|
2095
|
+
result = await enrichTransfers(result, apiInstance, chain);
|
|
2096
|
+
} finally {
|
|
2097
|
+
apiInstance.paginatedResponseMeta = transferPaginationMeta;
|
|
2098
|
+
apiInstance.paginatedEndpoint = transferPaginationEndpoint;
|
|
2099
|
+
}
|
|
1871
2100
|
}
|
|
1872
2101
|
|
|
1873
2102
|
return result;
|
|
@@ -2240,6 +2469,31 @@ export function generateSubcommandHelp(command, subcommand, prefix = null) {
|
|
|
2240
2469
|
return lines.join('\n');
|
|
2241
2470
|
}
|
|
2242
2471
|
|
|
2472
|
+
function emitResponseMetadata(api, errorOutput) {
|
|
2473
|
+
if (!api) return;
|
|
2474
|
+
const responseMeta = api.paginatedResponseMeta || api.lastResponseMeta;
|
|
2475
|
+
const lowCredits = creditWarning(responseMeta);
|
|
2476
|
+
if (lowCredits) errorOutput(lowCredits);
|
|
2477
|
+
for (const notice of noticeWarnings(responseMeta)) errorOutput(notice);
|
|
2478
|
+
|
|
2479
|
+
// An aggregate belongs to the primary paginated endpoint even if a composite
|
|
2480
|
+
// handler made auxiliary requests afterward and changed lastEndpoint.
|
|
2481
|
+
const endpoint = api.paginatedResponseMeta ? api.paginatedEndpoint : api.lastEndpoint;
|
|
2482
|
+
const charged = creditsCharged(responseMeta, endpoint);
|
|
2483
|
+
if (charged?.source === 'header') {
|
|
2484
|
+
const paginationMeta = responseMeta?.pagination;
|
|
2485
|
+
let scope = 'this call';
|
|
2486
|
+
if (paginationMeta?.cachedPages > 0 && paginationMeta.livePages > 0) {
|
|
2487
|
+
scope = `${paginationMeta.livePages} live of ${paginationMeta.pagesFetched} page requests`;
|
|
2488
|
+
} else if (paginationMeta?.livePages > 1) scope = `${paginationMeta.livePages} page requests`;
|
|
2489
|
+
else if (paginationMeta?.livePages === 1) scope = '1 page request';
|
|
2490
|
+
else if (paginationMeta?.livePages === 0) scope = 'cached traversal';
|
|
2491
|
+
errorOutput(`Credits: ${charged.cost} (${scope})`);
|
|
2492
|
+
} else if (charged?.source === 'estimate') {
|
|
2493
|
+
errorOutput(`Credits: ~${charged.estimate.free} free / ${charged.estimate.pro} pro (estimated)`);
|
|
2494
|
+
}
|
|
2495
|
+
}
|
|
2496
|
+
|
|
2243
2497
|
// Run CLI with given args (returns result, allows custom output/exit handlers)
|
|
2244
2498
|
export async function runCLI(rawArgs, deps = {}) {
|
|
2245
2499
|
const {
|
|
@@ -2251,6 +2505,7 @@ export async function runCLI(rawArgs, deps = {}) {
|
|
|
2251
2505
|
// Output TTY controls human-vs-structured error rendering. Keep the
|
|
2252
2506
|
// existing `isTTY` seam for callers/tests that inject both terminal states.
|
|
2253
2507
|
isTTY = process.stdout.isTTY,
|
|
2508
|
+
env = process.env,
|
|
2254
2509
|
} = deps;
|
|
2255
2510
|
|
|
2256
2511
|
// Command-layer interactivity is intentionally governed by stdin. Besides
|
|
@@ -2268,6 +2523,8 @@ export async function runCLI(rawArgs, deps = {}) {
|
|
|
2268
2523
|
const inputInteractiveDeps = {
|
|
2269
2524
|
...deps,
|
|
2270
2525
|
isTTY: isInputTTY,
|
|
2526
|
+
stdoutTTY: isTTY === true,
|
|
2527
|
+
stdinTTY: isInputTTY === true,
|
|
2271
2528
|
promptFn: deps.promptFn ?? prompt,
|
|
2272
2529
|
confirmationPromptFn: deps.confirmationPromptFn ?? promptForConfirmation,
|
|
2273
2530
|
confirmationLog: deps.confirmationLog ?? errorOutput,
|
|
@@ -2278,6 +2535,13 @@ export async function runCLI(rawArgs, deps = {}) {
|
|
|
2278
2535
|
};
|
|
2279
2536
|
|
|
2280
2537
|
let parsed;
|
|
2538
|
+
let api;
|
|
2539
|
+
let responseMetadataEmitted = false;
|
|
2540
|
+
const emitResponseMetadataOnce = () => {
|
|
2541
|
+
if (responseMetadataEmitted) return;
|
|
2542
|
+
responseMetadataEmitted = true;
|
|
2543
|
+
emitResponseMetadata(api, errorOutput);
|
|
2544
|
+
};
|
|
2281
2545
|
try {
|
|
2282
2546
|
parsed = parseArgs(rawArgs);
|
|
2283
2547
|
} catch (error) {
|
|
@@ -2294,27 +2558,34 @@ export async function runCLI(rawArgs, deps = {}) {
|
|
|
2294
2558
|
const subArgs = positional.slice(1);
|
|
2295
2559
|
const subcommand = subArgs[0];
|
|
2296
2560
|
|
|
2297
|
-
|
|
2561
|
+
// `--debug` turns on the request trace for the rest of the process. Set
|
|
2562
|
+
// before anything can make a request, and only when the flag is present so
|
|
2563
|
+
// NANSEN_DEBUG=1 still decides on its own when the flag is absent.
|
|
2564
|
+
if (flags.debug) setDebugEnabled(true);
|
|
2298
2565
|
|
|
2299
2566
|
const pretty = flags.pretty || flags.p;
|
|
2300
2567
|
const table = flags.table || flags.t;
|
|
2301
2568
|
const stream = flags.stream || flags.s;
|
|
2302
2569
|
const csv = options.format === 'csv';
|
|
2303
2570
|
|
|
2304
|
-
//
|
|
2305
|
-
//
|
|
2306
|
-
//
|
|
2571
|
+
// Commands in this set promise zero network activity. That includes update
|
|
2572
|
+
// checks, cost-map refreshes and telemetry, not just their primary work.
|
|
2573
|
+
// `cache` belongs here specifically so inspecting or clearing caches cannot
|
|
2574
|
+
// recreate update/telemetry state during the same invocation.
|
|
2307
2575
|
const isMcpUsage = command === 'mcp' && (subcommand !== 'verify' || flags.help || flags.h);
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2576
|
+
const isAuthMutation = command === 'login' || command === 'logout';
|
|
2577
|
+
const isOfflineCommand = command === 'auth'
|
|
2578
|
+
|| (command === 'doctor' && flags.offline)
|
|
2579
|
+
|| isMcpUsage
|
|
2580
|
+
|| command === 'completion'
|
|
2581
|
+
|| command === 'cache';
|
|
2582
|
+
const trackSucceeded = isOfflineCommand ? async () => {} : isAuthMutation ? metadata => trackAuthCommand({ ...metadata, command }) : trackCommandSucceeded;
|
|
2583
|
+
const trackFailed = isOfflineCommand ? async () => {} : isAuthMutation ? metadata => trackAuthCommand({ ...metadata, command, failed: true }) : trackCommandFailed;
|
|
2313
2584
|
|
|
2314
2585
|
// Update check (read cached result + schedule background refresh)
|
|
2315
|
-
const updateNotification = getUpdateNotification(VERSION);
|
|
2316
|
-
const upgradeNotice = getUpgradeNotice(VERSION);
|
|
2317
|
-
if (!isOfflineCommand) scheduleUpdateCheck();
|
|
2586
|
+
const updateNotification = isOfflineCommand ? null : getUpdateNotification(VERSION);
|
|
2587
|
+
const upgradeNotice = isOfflineCommand ? null : getUpgradeNotice(VERSION);
|
|
2588
|
+
if (!isOfflineCommand && !isAuthMutation) scheduleUpdateCheck();
|
|
2318
2589
|
const notify = () => {
|
|
2319
2590
|
if (upgradeNotice) errorOutput(upgradeNotice);
|
|
2320
2591
|
if (updateNotification) errorOutput(updateNotification);
|
|
@@ -2343,7 +2614,7 @@ export async function runCLI(rawArgs, deps = {}) {
|
|
|
2343
2614
|
if (command === 'help' || flags.help || flags.h) {
|
|
2344
2615
|
// Help for an offline command still owes the zero-network contract: the
|
|
2345
2616
|
// cost-map refresh fetches the OpenAPI spec and writes ~/.nansen/cost-map.json.
|
|
2346
|
-
if (!isOfflineCommand) await refreshCostMapIfStale();
|
|
2617
|
+
if (!isOfflineCommand && !isAuthMutation) await refreshCostMapIfStale();
|
|
2347
2618
|
// Check for subcommand-specific help: nansen <command> <subcommand> --help
|
|
2348
2619
|
if (flags.help || flags.h) {
|
|
2349
2620
|
// Handle 'research <category> <sub> --help' (3-level)
|
|
@@ -2396,8 +2667,8 @@ export async function runCLI(rawArgs, deps = {}) {
|
|
|
2396
2667
|
}
|
|
2397
2668
|
}
|
|
2398
2669
|
// Then try command-level help (list subcommands)
|
|
2399
|
-
// Skip for 'trade'/'alerts' — let the handler show its own usage
|
|
2400
|
-
const cmdSchemaLookup = command !== 'trade' && command !== 'alerts' && command !== 'agent' && (SCHEMA.commands[command] || SCHEMA.commands.research.subcommands[command]);
|
|
2670
|
+
// Skip for 'trade'/'alerts'/'cache' — let the handler show its own usage
|
|
2671
|
+
const cmdSchemaLookup = command !== 'trade' && command !== 'alerts' && command !== 'agent' && command !== 'cache' && (SCHEMA.commands[command] || SCHEMA.commands.research.subcommands[command]);
|
|
2401
2672
|
if (command && cmdSchemaLookup) {
|
|
2402
2673
|
const cmdSchema = cmdSchemaLookup;
|
|
2403
2674
|
const lines = [`${command} — ${cmdSchema.description}`];
|
|
@@ -2427,9 +2698,8 @@ export async function runCLI(rawArgs, deps = {}) {
|
|
|
2427
2698
|
// Prevents destructive commands like logout from running when user just wants help
|
|
2428
2699
|
if (commands[command]) {
|
|
2429
2700
|
const simpleHelp = {
|
|
2430
|
-
'logout': 'nansen logout — Remove saved API key from ~/.nansen/config.json',
|
|
2431
2701
|
'schema': 'nansen schema [command] [--pretty] — Show JSON schema for all commands (or a specific command)',
|
|
2432
|
-
'cache':
|
|
2702
|
+
'cache': CACHE_HELP,
|
|
2433
2703
|
};
|
|
2434
2704
|
if (simpleHelp[command]) {
|
|
2435
2705
|
output(simpleHelp[command]);
|
|
@@ -2491,7 +2761,10 @@ export async function runCLI(rawArgs, deps = {}) {
|
|
|
2491
2761
|
// Configure cache options
|
|
2492
2762
|
const cacheTtl = parseNonNegativeSafeIntegerOption('cache-ttl', options, flags, 300);
|
|
2493
2763
|
const cacheOptions = {
|
|
2494
|
-
|
|
2764
|
+
// NANSEN_NO_CACHE is the flagless form of --no-cache, for callers that
|
|
2765
|
+
// cannot edit the command line (a wrapper script or agent harness that
|
|
2766
|
+
// always passes --cache). Both are a veto, never an enable.
|
|
2767
|
+
enabled: flags['cache'] && !flags['no-cache'] && env.NANSEN_NO_CACHE !== '1',
|
|
2495
2768
|
ttl: cacheTtl
|
|
2496
2769
|
};
|
|
2497
2770
|
|
|
@@ -2499,7 +2772,16 @@ export async function runCLI(rawArgs, deps = {}) {
|
|
|
2499
2772
|
if (options['x402-payment-signature']) {
|
|
2500
2773
|
defaultHeaders['Payment-Signature'] = options['x402-payment-signature'];
|
|
2501
2774
|
}
|
|
2502
|
-
|
|
2775
|
+
api = new NansenAPIClass(undefined, undefined, { retry: retryOptions, cache: cacheOptions, defaultHeaders, authState: inputInteractiveDeps.authState });
|
|
2776
|
+
|
|
2777
|
+
// --all aliases --paginate; wrapping api.request gives every list handler
|
|
2778
|
+
// the same max-pages bound while leaving non-list requests untouched.
|
|
2779
|
+
if (flags.paginate || flags.all) {
|
|
2780
|
+
const maxPages = parsePositiveSafeIntegerOption(
|
|
2781
|
+
'max-pages', options, flags, DEFAULT_MAX_PAGES, { max: MAX_PAGES_LIMIT },
|
|
2782
|
+
);
|
|
2783
|
+
enableAutoPagination(api, { maxPages });
|
|
2784
|
+
}
|
|
2503
2785
|
|
|
2504
2786
|
// Deprecated top-level aliases otherwise run silently (the notice was only
|
|
2505
2787
|
// shown in --help). Warn on stderr so it doesn't pollute parsed stdout.
|
|
@@ -2528,18 +2810,7 @@ export async function runCLI(rawArgs, deps = {}) {
|
|
|
2528
2810
|
// stderr so it never contaminates the JSON on stdout that agents parse.
|
|
2529
2811
|
// Placed before every return path below so it fires for operational
|
|
2530
2812
|
// commands too, which print their own output and return undefined.
|
|
2531
|
-
|
|
2532
|
-
if (lowCredits) errorOutput(lowCredits);
|
|
2533
|
-
for (const notice of noticeWarnings(api.lastResponseMeta)) errorOutput(notice);
|
|
2534
|
-
|
|
2535
|
-
// What this call cost — authoritative header when the API sent one, else
|
|
2536
|
-
// the cached spec estimate. stderr only, so stdout JSON stays pure.
|
|
2537
|
-
const charged = creditsCharged(api.lastResponseMeta, api.lastEndpoint);
|
|
2538
|
-
if (charged?.source === 'header') {
|
|
2539
|
-
errorOutput(`Credits: ${charged.cost} (this call)`);
|
|
2540
|
-
} else if (charged?.source === 'estimate') {
|
|
2541
|
-
errorOutput(`Credits: ~${charged.estimate.free} free / ${charged.estimate.pro} pro (estimated)`);
|
|
2542
|
-
}
|
|
2813
|
+
emitResponseMetadataOnce();
|
|
2543
2814
|
|
|
2544
2815
|
// Commands that handle their own output return undefined
|
|
2545
2816
|
if (result === undefined) {
|
|
@@ -2585,6 +2856,9 @@ export async function runCLI(rawArgs, deps = {}) {
|
|
|
2585
2856
|
await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
|
|
2586
2857
|
return { type: csv ? 'csv' : 'success', data: result };
|
|
2587
2858
|
} catch (error) {
|
|
2859
|
+
// A failed later page can still have incurred charges on earlier pages.
|
|
2860
|
+
// Emit the aggregate on stderr before serializing the unchanged error.
|
|
2861
|
+
emitResponseMetadataOnce();
|
|
2588
2862
|
// Unified error envelope across all command families (perp/bridge/trade):
|
|
2589
2863
|
// every failure serializes through formatError as
|
|
2590
2864
|
// {success:false, error, code, status, details}. A CommandError's structured
|