nansen-cli 1.43.1 → 1.44.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/src/bridge.js CHANGED
@@ -1077,6 +1077,56 @@ export async function resolveEvmStepFees(chain, txData, overrides = {}) {
1077
1077
  return { gasPrice: await evmRpcCall(chain, 'eth_gasPrice') };
1078
1078
  }
1079
1079
 
1080
+ // eth_sendRawTransaction JSON-RPC error messages that PROVE the tx never
1081
+ // entered the mempool: the node rejected it during validation, so nothing is in
1082
+ // flight and the quote stays reusable. Matched case-insensitively as substrings
1083
+ // of the node's error text. Every entry here must be UNAMBIGUOUSLY pre-broadcast
1084
+ // across EVM node implementations. Everything NOT listed fails closed — crucially
1085
+ // the txpool states ("already known", "known transaction", "already imported",
1086
+ // "nonce too low", "replacement transaction underpriced") that mean a tx is
1087
+ // ALREADY in flight; treating those as safe rejections would let a re-execute
1088
+ // sign a fresh nonce and broadcast a second bridge tx.
1089
+ //
1090
+ // Deliberately EXCLUDED: the bare "transaction underpriced". On go-ethereum /
1091
+ // op-geth (which is what Base — today's only EVM bridge chain — runs) it means a
1092
+ // fresh too-low-fee tx that was never accepted, i.e. safe. But some other nodes
1093
+ // (certain Besu / Nethermind versions) reuse that same bare message for a failed
1094
+ // REPLACEMENT (a nonce collision with an in-flight tx). Since the allowlist is
1095
+ // not chain-scoped and processEvmStep runs for whatever CHAIN_RPCS resolves, we
1096
+ // fail closed on it rather than risk a future non-geth chain misclassifying an
1097
+ // in-flight tx as safe. Cost is at most a needless re-quote.
1098
+ const PRE_BROADCAST_SEND_ERRORS = [
1099
+ 'insufficient funds',
1100
+ 'intrinsic gas too low',
1101
+ 'gas too low',
1102
+ 'exceeds block gas limit',
1103
+ 'exceeds the block gas limit',
1104
+ 'max fee per gas less than block base fee',
1105
+ 'fee cap less than block base fee',
1106
+ 'max priority fee per gas higher than max fee per gas',
1107
+ 'invalid sender',
1108
+ 'invalid signature',
1109
+ 'could not decode',
1110
+ 'rlp: ', // geth's RLP decode errors ("rlp: input string too long", …); the
1111
+ // trailing space avoids matching "rlp" embedded in an unrelated message
1112
+ 'negative value',
1113
+ ];
1114
+
1115
+ // True when we are CONFIDENT a failed send never put the tx into the mempool, so
1116
+ // the bridge quote may be retried. This is deliberately NARROW: a definitive
1117
+ // answer requires a JSON-RPC rejection (RPC_JSON_ERROR) whose message is on the
1118
+ // pre-broadcast allowlist, or a missing-RPC config error (the request never
1119
+ // left this process). A transport/HTTP failure, or ANY other JSON-RPC error
1120
+ // (including in-flight txpool states and the cross-node-ambiguous bare
1121
+ // "transaction underpriced"), is treated as unsafe and must fail closed — see
1122
+ // evmRpcCall (trading.js) for the error codes.
1123
+ function isPreBroadcastSendRejection(err) {
1124
+ if (err?.code === 'RPC_UNCONFIGURED') return true;
1125
+ if (err?.code !== 'RPC_JSON_ERROR') return false;
1126
+ const msg = (err.message || '').toLowerCase();
1127
+ return PRE_BROADCAST_SEND_ERRORS.some(pattern => msg.includes(pattern));
1128
+ }
1129
+
1080
1130
  async function processEvmStep(step, { chain, privateKeyHex, signerAddress, log, onBroadcast, feeOverrides, nonceSequence, intent }) {
1081
1131
  for (const item of step.items || []) {
1082
1132
  if (item.status === 'complete') continue;
@@ -1114,7 +1164,20 @@ async function processEvmStep(step, { chain, privateKeyHex, signerAddress, log,
1114
1164
  );
1115
1165
 
1116
1166
  log(` Broadcasting ${step.id} on ${chain}...`);
1117
- const txHash = await evmRpcCall(chain, 'eth_sendRawTransaction', [signedTx]);
1167
+ let txHash;
1168
+ try {
1169
+ txHash = await evmRpcCall(chain, 'eth_sendRawTransaction', [signedTx]);
1170
+ } catch (sendErr) {
1171
+ // Fail closed UNLESS we're confident the tx never entered the mempool (a
1172
+ // pre-broadcast validation rejection, or no RPC configured). Everything
1173
+ // else — a lost ack, a gateway error, OR an in-flight txpool state like
1174
+ // "already known" / "nonce too low" that a node reports as a JSON-RPC
1175
+ // error — may already be broadcasting, so mark the quote spent before
1176
+ // rethrowing to abort, so a later re-execute can't re-sign this step at a
1177
+ // fresh nonce and double-broadcast.
1178
+ if (!isPreBroadcastSendRejection(sendErr)) onBroadcast?.(step.id, null);
1179
+ throw sendErr;
1180
+ }
1118
1181
  // In flight now: record it before waiting on the receipt, because a receipt
1119
1182
  // timeout must not leave the quote reusable.
1120
1183
  onBroadcast?.(step.id, txHash);
@@ -1158,7 +1221,16 @@ async function processSignatureStepLocal(step, { privateKeyHex, log, apiInstance
1158
1221
  }
1159
1222
 
1160
1223
  log(` Signing ${step.id} (EIP-712)...`);
1161
- await postBridgeExecute(apiInstance, targetUrl, postBody);
1224
+ // Fail closed on ANY submit failure: the proxy may have forwarded the
1225
+ // authorization before the error surfaced, and we can't tell that from a
1226
+ // clean pre-forward rejection. Consume the quote before rethrowing so a
1227
+ // re-execute can't resubmit this leg.
1228
+ try {
1229
+ await postBridgeExecute(apiInstance, targetUrl, postBody);
1230
+ } catch (sendErr) {
1231
+ onBroadcast?.(step.id, null);
1232
+ throw sendErr;
1233
+ }
1162
1234
  onBroadcast?.(step.id, null);
1163
1235
  log(` Submitted to ${new URL(targetUrl).hostname}`);
1164
1236
  } else if (signData.action) {
@@ -1196,7 +1268,17 @@ async function processSignatureStepLocal(step, { privateKeyHex, log, apiInstance
1196
1268
  };
1197
1269
 
1198
1270
  log(` Signing ${step.id} (Hyperliquid deposit)...`);
1199
- const result = await postBridgeExecute(apiInstance, 'https://api.hyperliquid.xyz/exchange', hlBody);
1271
+ // Fail closed if the SUBMIT itself throws (transport/proxy error — HL may
1272
+ // still have received the action). A clean HL rejection instead returns
1273
+ // 200 and is caught by assertHyperliquidStepAccepted below, OUTSIDE this
1274
+ // try: that is a definitive no-op, so it must NOT consume the quote.
1275
+ let result;
1276
+ try {
1277
+ result = await postBridgeExecute(apiInstance, 'https://api.hyperliquid.xyz/exchange', hlBody);
1278
+ } catch (sendErr) {
1279
+ onBroadcast?.(step.id, null);
1280
+ throw sendErr;
1281
+ }
1200
1282
  assertHyperliquidStepAccepted(result, step.id);
1201
1283
  onBroadcast?.(step.id, null);
1202
1284
  log(` Submitted to api.hyperliquid.xyz`);
@@ -1270,7 +1352,14 @@ async function processSignatureStepPrivy(step, { privyClient, walletId, log, api
1270
1352
  } else {
1271
1353
  postBody.signature = signature;
1272
1354
  }
1273
- await postBridgeExecute(apiInstance, targetUrl, postBody);
1355
+ // Fail closed on any submit failure — see the local path for the rationale
1356
+ // (an ambiguous forward must not leave the quote reusable).
1357
+ try {
1358
+ await postBridgeExecute(apiInstance, targetUrl, postBody);
1359
+ } catch (sendErr) {
1360
+ onBroadcast?.(step.id, null);
1361
+ throw sendErr;
1362
+ }
1274
1363
  onBroadcast?.(step.id, null);
1275
1364
  } else {
1276
1365
  const [rHex, sHex, vHex] = [signature.slice(2, 66), signature.slice(66, 130), signature.slice(130, 132)];
@@ -1279,7 +1368,16 @@ async function processSignatureStepPrivy(step, { privyClient, walletId, log, api
1279
1368
  nonce: signData.nonce,
1280
1369
  signature: { r: '0x' + rHex, s: '0x' + sHex, v: parseInt(vHex, 16) },
1281
1370
  };
1282
- const result = await postBridgeExecute(apiInstance, 'https://api.hyperliquid.xyz/exchange', hlBody);
1371
+ // Submit-throw = ambiguous → fail closed; a clean HL rejection returns 200
1372
+ // and is caught by assertHyperliquidStepAccepted (outside the try) as a
1373
+ // definitive no-op that must NOT consume the quote.
1374
+ let result;
1375
+ try {
1376
+ result = await postBridgeExecute(apiInstance, 'https://api.hyperliquid.xyz/exchange', hlBody);
1377
+ } catch (sendErr) {
1378
+ onBroadcast?.(step.id, null);
1379
+ throw sendErr;
1380
+ }
1283
1381
  assertHyperliquidStepAccepted(result, step.id);
1284
1382
  onBroadcast?.(step.id, null);
1285
1383
  }
package/src/cli.js CHANGED
@@ -12,8 +12,12 @@ import { buildLimitOrderCommands } from './limit-order.js';
12
12
  import { formatAlertsTable, buildAlertsCommands } from './commands/alerts.js';
13
13
  import { buildAgentCommands } from './commands/agent.js';
14
14
  import { buildMcpCommands } from './commands/mcp.js';
15
- import { buildResearchCommands, RESEARCH_HISTORICAL_SUBCOMMANDS } from './commands/research.js';
15
+ import { buildCompletionCommands } from './commands/completion.js';
16
+ import { buildResearchCommands, RESEARCH_HISTORICAL_SUBCOMMANDS, RESEARCH_SUBCOMMANDS } from './commands/research.js';
17
+ import { buildPagination, parseSort } from './query-options.js';
18
+ export { buildPagination, parseSort };
16
19
  import { resolveAddress, isEnsName } from './ens.js';
20
+ import { compareSemver } from './semver.js';
17
21
  import fs from 'fs';
18
22
  import { getUpdateNotification, getUpgradeNotice, scheduleUpdateCheck } from './update-check.js';
19
23
  import { getAuthStatus, runDoctorChecks, runConnectivityChecks, formatDoctorReport } from './doctor.js';
@@ -54,14 +58,6 @@ export function resolveBooleanOption(options, flags, key) {
54
58
  return undefined;
55
59
  }
56
60
 
57
- export function buildPagination(options) {
58
- if (!options.limit && !options.page) return undefined;
59
- return {
60
- page: Math.max(1, parseInt(options.page, 10) || 1),
61
- per_page: options.limit,
62
- };
63
- }
64
-
65
61
  // ============= Field Filtering =============
66
62
 
67
63
  /**
@@ -168,18 +164,15 @@ export function compactSchema(schema) {
168
164
  };
169
165
  }
170
166
 
171
- /**
172
- * Compare two semver strings. Returns 1 if a > b, -1 if a < b, 0 if equal.
173
- */
174
- function compareSemver(a, b) {
175
- const parse = v => v.replace(/^v/, '').split('.').map(Number);
176
- const [aM, am, ap] = parse(a);
177
- const [bM, bm, bp] = parse(b);
178
- if (aM !== bM) return aM > bM ? 1 : -1;
179
- if (am !== bm) return am > bm ? 1 : -1;
180
- if (ap !== bp) return ap > bp ? 1 : -1;
181
- return 0;
182
- }
167
+ // Long options that never consume the next argument. The shell-completion
168
+ // generator needs the same list to tell an option's value apart from a
169
+ // subcommand, so it lives here rather than inline in parseArgs.
170
+ export const VALUELESS_FLAGS = new Set([
171
+ 'pretty', 'help', 'version', 'table', 'no-retry', 'cache', 'no-cache', 'stream',
172
+ 'enrich', 'full', 'human', 'enabled', 'disabled', 'expert', 'json', 'offline',
173
+ 'no-simulate', 'no-verify-outcome', 'no-revoke-excessive-allowance', 'dry-run',
174
+ 'send-api-key',
175
+ ]);
183
176
 
184
177
  export function parseArgs(args) {
185
178
  const result = { _: [], flags: {}, options: {} };
@@ -191,7 +184,7 @@ export function parseArgs(args) {
191
184
  const key = arg.slice(2);
192
185
  const next = args[i + 1];
193
186
 
194
- if (key === 'pretty' || key === 'help' || key === 'version' || key === 'table' || key === 'no-retry' || key === 'cache' || key === 'no-cache' || key === 'stream' || key === 'enrich' || key === 'full' || key === 'human' || key === 'enabled' || key === 'disabled' || key === 'expert' || key === 'json' || key === 'offline' || key === 'no-simulate' || key === 'no-verify-outcome' || key === 'no-revoke-excessive-allowance' || key === 'dry-run') {
187
+ if (VALUELESS_FLAGS.has(key)) {
195
188
  result.flags[key] = true;
196
189
  } else if (next && (!next.startsWith('-') || /^-\d/.test(next))) {
197
190
  // Try to parse as JSON first (for objects/arrays/booleans),
@@ -227,6 +220,40 @@ export function parseArgs(args) {
227
220
  return result;
228
221
  }
229
222
 
223
+ function parseNonNegativeSafeIntegerOption(name, options, flags, defaultValue) {
224
+ if (flags[name]) {
225
+ throw new NansenError(
226
+ `--${name} requires a non-negative safe integer value`,
227
+ ErrorCode.INVALID_PARAMS,
228
+ );
229
+ }
230
+ if (options[name] === undefined) return defaultValue;
231
+
232
+ const rawValue = options[name];
233
+ if (Array.isArray(rawValue)) {
234
+ throw new NansenError(
235
+ `--${name} may only be specified once`,
236
+ ErrorCode.INVALID_PARAMS,
237
+ );
238
+ }
239
+ if (typeof rawValue === 'string' && rawValue.trim() === '') {
240
+ throw new NansenError(
241
+ `--${name} requires a non-negative safe integer value`,
242
+ ErrorCode.INVALID_PARAMS,
243
+ );
244
+ }
245
+ const value = typeof rawValue === 'string' || typeof rawValue === 'number'
246
+ ? Number(rawValue)
247
+ : NaN;
248
+ if (!Number.isSafeInteger(value) || value < 0) {
249
+ throw new NansenError(
250
+ `--${name} must be a non-negative safe integer; received: ${String(rawValue)}`,
251
+ ErrorCode.INVALID_PARAMS,
252
+ );
253
+ }
254
+ return value;
255
+ }
256
+
230
257
  // Format a single value for table display
231
258
  export function formatValue(val) {
232
259
  if (val === null || val === undefined) return '';
@@ -460,22 +487,6 @@ export function parseDateOption(dateOption, days = 30) {
460
487
  return { from, to };
461
488
  }
462
489
 
463
- // Parse simple sort syntax: "field:direction" or "field" (defaults to DESC)
464
- export function parseSort(sortOption, orderByOption) {
465
- // If --order-by is provided, use it (full JSON control)
466
- if (orderByOption) return orderByOption;
467
-
468
- // If no --sort, return undefined
469
- if (!sortOption) return undefined;
470
-
471
- // Parse --sort field:direction or --sort field
472
- const parts = sortOption.split(':');
473
- const field = parts[0];
474
- const direction = (parts[1] || 'desc').toUpperCase();
475
-
476
- return [{ field, direction }];
477
- }
478
-
479
490
  // Enrich transfers with Nansen labels for from/to addresses
480
491
  async function enrichTransfers(result, apiInstance, chain) {
481
492
  const transfers = result?.data?.results || result?.transfers || result?.data || [];
@@ -746,6 +757,7 @@ COMMANDS:
746
757
  logout Remove saved API key
747
758
  doctor Diagnostics: auth, wallets, caches, connectivity (--offline --json)
748
759
  schema JSON schema for all commands (use "nansen schema <cmd>" for one)
760
+ completion Shell completions: bash, zsh, fish
749
761
  cache clear
750
762
  changelog --since <version> to filter
751
763
 
@@ -785,7 +797,7 @@ Labels: Fund, Smart Trader, 30D/90D/180D Smart Trader, Smart HL Perps Trader
785
797
  Docs: https://docs.nansen.ai
786
798
  Skills: npx skills add nansen-ai/nansen-cli (agent-optimised docs per command group)
787
799
 
788
- Telemetry: anonymous usage stats (commands, timing, errors). Perp order/close additionally send the order side and Hyperliquid order id. Disable: DO_NOT_TRACK=1
800
+ 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
789
801
  `;
790
802
 
791
803
  // Usage text for the `trade` command group. Shared by the trade handler and the
@@ -1132,6 +1144,15 @@ export function buildCommands(deps = {}) {
1132
1144
  }
1133
1145
  const since = _options.since;
1134
1146
  if (since) {
1147
+ // compareSemver treats a missing trailing component as 0, so accept
1148
+ // "1", "1.43", and "1.43.0" alike here — but anything that isn't
1149
+ // digits-and-dots (e.g. "abc") needs a clear error instead of
1150
+ // silently comparing as if it were version 0.0.0, which would show
1151
+ // every entry rather than flag the typo.
1152
+ if (!/^v?\d+(\.\d+){0,2}$/.test(String(since))) {
1153
+ log(`Invalid --since value "${since}": expected a version like 1.43 or 1.43.0.`);
1154
+ return;
1155
+ }
1135
1156
  // Show only entries from the given version onwards
1136
1157
  const lines = content.split('\n');
1137
1158
  const filtered = [];
@@ -1193,7 +1214,7 @@ export function buildCommands(deps = {}) {
1193
1214
  log('CACHE OPTIONS (for any command):');
1194
1215
  log(' --cache Enable caching for this session');
1195
1216
  log(' --no-cache Bypass cache for this request');
1196
- log(' --cache-ttl <seconds> Set cache TTL (default: 300)');
1217
+ log(' --cache-ttl <seconds> Set non-negative safe integer cache TTL (default: 300)');
1197
1218
  }
1198
1219
  };
1199
1220
 
@@ -1530,7 +1551,7 @@ export function buildCommands(deps = {}) {
1530
1551
  };
1531
1552
 
1532
1553
  if (!handlers[subcommand]) {
1533
- return { error: `Unknown subcommand: ${subcommand}`, available: Object.keys(handlers) };
1554
+ throw new NansenError(`Unknown perp analytics subcommand: ${subcommand}. Available: screener, leaderboard`, ErrorCode.UNKNOWN);
1534
1555
  }
1535
1556
 
1536
1557
  return handlers[subcommand]();
@@ -1587,7 +1608,7 @@ export function buildCommands(deps = {}) {
1587
1608
  const maxUniqueTraders24h = options['max-unique-traders-24h'] != null ? Number(options['max-unique-traders-24h']) : undefined;
1588
1609
  const minVolume24hr = options['min-volume-24hr'] != null ? Number(options['min-volume-24hr']) : undefined;
1589
1610
  const maxVolume24hr = options['max-volume-24hr'] != null ? Number(options['max-volume-24hr']) : undefined;
1590
- const negRisk = options['neg-risk'] != null ? options['neg-risk'] === 'true' : undefined;
1611
+ const negRisk = resolveBooleanOption(options, flags, 'neg-risk');
1591
1612
  const minOpenInterest = options['min-open-interest'] != null ? Number(options['min-open-interest']) : undefined;
1592
1613
  const maxOpenInterest = options['max-open-interest'] != null ? Number(options['max-open-interest']) : undefined;
1593
1614
  const endDateBefore = options['end-date-before'];
@@ -1631,32 +1652,33 @@ export function buildCommands(deps = {}) {
1631
1652
  // it, so it has to be taken exactly once, here.
1632
1653
  const perpAnalytics = cmds['perp'];
1633
1654
 
1634
- const researchHistorical = buildResearchCommands(deps).research;
1655
+ const researchSub = buildResearchCommands(deps).research;
1635
1656
 
1636
1657
  cmds['research'] = async (args, apiInstance, flags, options) => {
1637
1658
  const rawCategory = args[0];
1638
1659
  if (!rawCategory || rawCategory === 'help') {
1639
1660
  return {
1640
1661
  categories: [...RESEARCH_CATEGORIES],
1662
+ subcommands: [...RESEARCH_SUBCOMMANDS],
1641
1663
  historical: [...RESEARCH_HISTORICAL_SUBCOMMANDS],
1642
1664
  aliases: RESEARCH_CATEGORY_ALIASES,
1643
1665
  description: 'Research and analytics commands',
1644
1666
  example: 'nansen research smart-money netflow --chain solana'
1645
1667
  };
1646
1668
  }
1647
- if (RESEARCH_HISTORICAL_SUBCOMMANDS.has(rawCategory)) {
1648
- return researchHistorical(args, apiInstance, flags, options);
1669
+ if (RESEARCH_SUBCOMMANDS.has(rawCategory)) {
1670
+ return researchSub(args, apiInstance, flags, options);
1649
1671
  }
1650
1672
  const category = RESEARCH_CATEGORY_ALIASES[rawCategory] || rawCategory;
1651
1673
  if (!RESEARCH_CATEGORIES.has(category)) {
1652
- throw new NansenError(`Unknown research category: ${rawCategory}. Available: ${[...RESEARCH_CATEGORIES, ...RESEARCH_HISTORICAL_SUBCOMMANDS].join(', ')}`, ErrorCode.UNKNOWN);
1674
+ throw new NansenError(`Unknown research category: ${rawCategory}. Available: ${[...RESEARCH_CATEGORIES, ...RESEARCH_SUBCOMMANDS].join(', ')}`, ErrorCode.UNKNOWN);
1653
1675
  }
1654
1676
  // `research perp` reaches only the analytics half (screener/leaderboard) —
1655
- // the trading subcommands live at the top level. Routing its help through
1656
- // cmds['perp'] printed the trading help, advertising order/close/leverage
1657
- // from a command that can't run them.
1658
- if (category === 'perp' && (!args[1] || args[1] === 'help')) {
1659
- return perpAnalytics(['help'], apiInstance, flags, options);
1677
+ // the trading subcommands live at the top level. Use the captured handler
1678
+ // for every subcommand because cmds['perp'] is replaced below by the
1679
+ // combined top-level trading dispatcher.
1680
+ if (category === 'perp') {
1681
+ return perpAnalytics(args.slice(1), apiInstance, flags, options);
1660
1682
  }
1661
1683
  return cmds[category](args.slice(1), apiInstance, flags, options);
1662
1684
  };
@@ -1877,7 +1899,9 @@ export async function runCLI(rawArgs, deps = {}) {
1877
1899
  // contract covers the background update-check fetch and telemetry too,
1878
1900
  // not just the command's own requests.
1879
1901
  const isMcpUsage = command === 'mcp' && (subcommand !== 'verify' || flags.help || flags.h);
1880
- const isOfflineCommand = command === 'auth' || (command === 'doctor' && flags.offline) || isMcpUsage;
1902
+ // `completion` renders from the checked-in schema — no network, and its
1903
+ // stdout is piped straight into a shell, so keep the update check out of it.
1904
+ const isOfflineCommand = command === 'auth' || (command === 'doctor' && flags.offline) || isMcpUsage || command === 'completion';
1881
1905
  const trackSucceeded = isOfflineCommand ? async () => {} : trackCommandSucceeded;
1882
1906
  const trackFailed = isOfflineCommand ? async () => {} : trackCommandFailed;
1883
1907
 
@@ -1899,7 +1923,7 @@ export async function runCLI(rawArgs, deps = {}) {
1899
1923
 
1900
1924
  // mcp prints its own output via `log`; runCLI callers inject their stdout
1901
1925
  // sink as `output`, so map it across (an explicit `log` dep still wins).
1902
- const commands = { ...buildCommands(deps), ...buildWalletCommands(deps), ...buildTradingCommands(deps), ...buildAlertsCommands(deps), ...buildAgentCommands(deps), ...buildMcpCommands({ ...deps, log: deps.log ?? output }), ...commandOverrides };
1926
+ const commands = { ...buildCommands(deps), ...buildWalletCommands(deps), ...buildTradingCommands(deps), ...buildAlertsCommands(deps), ...buildAgentCommands(deps), ...buildMcpCommands({ ...deps, log: deps.log ?? output }), ...buildCompletionCommands({ ...deps, log: deps.log ?? output }), ...commandOverrides };
1903
1927
 
1904
1928
  if (flags.version || flags.v) {
1905
1929
  output(VERSION);
@@ -2049,15 +2073,16 @@ export async function runCLI(rawArgs, deps = {}) {
2049
2073
 
2050
2074
  try {
2051
2075
  // Configure retry options
2076
+ const maxRetries = parseNonNegativeSafeIntegerOption('retries', options, flags, 3);
2052
2077
  const retryOptions = flags['no-retry']
2053
2078
  ? { maxRetries: 0 }
2054
- : { maxRetries: options.retries !== undefined ? (Number.isNaN(parseInt(options.retries, 10)) ? 3 : parseInt(options.retries, 10)) : 3 };
2079
+ : { maxRetries };
2055
2080
 
2056
2081
  // Configure cache options
2057
- const cacheTtl = options['cache-ttl'] !== undefined ? parseInt(options['cache-ttl'], 10) : 300;
2082
+ const cacheTtl = parseNonNegativeSafeIntegerOption('cache-ttl', options, flags, 300);
2058
2083
  const cacheOptions = {
2059
2084
  enabled: flags['cache'] && !flags['no-cache'],
2060
- ttl: Number.isNaN(cacheTtl) ? 300 : cacheTtl
2085
+ ttl: cacheTtl
2061
2086
  };
2062
2087
 
2063
2088
  const defaultHeaders = {};
@@ -107,15 +107,32 @@ function parseChains(chainsOpt) {
107
107
  return chainsOpt.split(',').map(s => s.trim()).filter(Boolean);
108
108
  }
109
109
 
110
+ /**
111
+ * Parse a CLI option value as a finite number, or throw a clear error.
112
+ *
113
+ * Plain `Number(val)` turns garbage input ("abc") into NaN, and
114
+ * `JSON.stringify` silently turns NaN into `null` — so a typo'd
115
+ * --usd-min/--market-cap-max/etc. would vanish from the request instead of
116
+ * failing loudly, and the alert would ship without the filter the user
117
+ * asked for.
118
+ */
119
+ function parseFiniteNumber(raw, name) {
120
+ const n = Number(raw);
121
+ if (!Number.isFinite(n)) {
122
+ throw new NansenError(`Invalid --${name} "${raw}": must be a number`, ErrorCode.INVALID_PARAMS);
123
+ }
124
+ return n;
125
+ }
126
+
110
127
  /**
111
128
  * Build a { min, max } range object from two option values.
112
129
  * Returns undefined if neither is provided.
113
130
  */
114
- function buildRange(minVal, maxVal) {
131
+ function buildRange(minVal, maxVal, name) {
115
132
  if (minVal === undefined && maxVal === undefined) return undefined;
116
133
  const r = {};
117
- if (minVal !== undefined) r.min = Number(minVal);
118
- if (maxVal !== undefined) r.max = Number(maxVal);
134
+ if (minVal !== undefined) r.min = parseFiniteNumber(minVal, `${name}-min`);
135
+ if (maxVal !== undefined) r.max = parseFiniteNumber(maxVal, `${name}-max`);
119
136
  return r;
120
137
  }
121
138
 
@@ -138,7 +155,7 @@ export function buildSmTokenFlowsData(options) {
138
155
 
139
156
  const flowFields = ['inflow-1h', 'inflow-1d', 'inflow-7d', 'outflow-1h', 'outflow-1d', 'outflow-7d', 'netflow-1h', 'netflow-1d', 'netflow-7d'];
140
157
  for (const field of flowFields) {
141
- const range = buildRange(options[`${field}-min`], options[`${field}-max`]);
158
+ const range = buildRange(options[`${field}-min`], options[`${field}-max`], field);
142
159
  if (range) {
143
160
  // Convert CLI key "inflow-1h" → data key "inflow_1h"
144
161
  data[field.replace(/-/g, '_')] = range;
@@ -156,13 +173,13 @@ export function buildSmTokenFlowsData(options) {
156
173
  if (excludeSectors) data.exclusion = { ...data.exclusion, tokenSectors: excludeSectors };
157
174
 
158
175
  if (options['token-age-max'] !== undefined) {
159
- data.inclusion = { ...data.inclusion, tokenAge: { max: Number(options['token-age-max']) } };
176
+ data.inclusion = { ...data.inclusion, tokenAge: { max: parseFiniteNumber(options['token-age-max'], 'token-age-max') } };
160
177
  }
161
178
 
162
- const marketCapRange = buildRange(options['market-cap-min'], options['market-cap-max']);
179
+ const marketCapRange = buildRange(options['market-cap-min'], options['market-cap-max'], 'market-cap');
163
180
  if (marketCapRange) data.inclusion = { ...data.inclusion, marketCap: marketCapRange };
164
181
 
165
- const fdvRange = buildRange(options['fdv-min'], options['fdv-max']);
182
+ const fdvRange = buildRange(options['fdv-min'], options['fdv-max'], 'fdv');
166
183
  if (fdvRange) data.inclusion = { ...data.inclusion, fdvUsd: fdvRange };
167
184
 
168
185
  return data;
@@ -181,10 +198,10 @@ export function buildCommonTokenTransferData(options) {
181
198
  data.events = typeof options.events === 'string' ? options.events.split(',') : options.events;
182
199
  }
183
200
 
184
- const usdRange = buildRange(options['usd-min'], options['usd-max']);
201
+ const usdRange = buildRange(options['usd-min'], options['usd-max'], 'usd');
185
202
  if (usdRange) data.usdValue = usdRange;
186
203
 
187
- const amountRange = buildRange(options['token-amount-min'], options['token-amount-max']);
204
+ const amountRange = buildRange(options['token-amount-min'], options['token-amount-max'], 'token-amount');
188
205
  if (amountRange) data.tokenAmount = amountRange;
189
206
 
190
207
  const subjects = parseSubjects(options.subject);
@@ -207,12 +224,12 @@ export function buildCommonTokenTransferData(options) {
207
224
  const tokenAgeMax = options['token-age-max'];
208
225
  if (tokenAgeMin !== undefined || tokenAgeMax !== undefined) {
209
226
  const tokenAge = {};
210
- if (tokenAgeMin !== undefined) tokenAge.min = Number(tokenAgeMin);
211
- if (tokenAgeMax !== undefined) tokenAge.max = Number(tokenAgeMax);
227
+ if (tokenAgeMin !== undefined) tokenAge.min = parseFiniteNumber(tokenAgeMin, 'token-age-min');
228
+ if (tokenAgeMax !== undefined) tokenAge.max = parseFiniteNumber(tokenAgeMax, 'token-age-max');
212
229
  data.inclusion = { ...data.inclusion, tokenAge };
213
230
  }
214
231
 
215
- const marketCapRange = buildRange(options['market-cap-min'], options['market-cap-max']);
232
+ const marketCapRange = buildRange(options['market-cap-min'], options['market-cap-max'], 'market-cap');
216
233
  if (marketCapRange) data.inclusion = { ...data.inclusion, marketCap: marketCapRange };
217
234
 
218
235
  const excludeFrom = parseSubjects(options['exclude-from']);
@@ -232,7 +249,7 @@ export function buildSmartContractCallData(options) {
232
249
  const chains = parseChains(options.chains);
233
250
  if (chains) data.chains = chains;
234
251
 
235
- const usdRange = buildRange(options['usd-min'], options['usd-max']);
252
+ const usdRange = buildRange(options['usd-min'], options['usd-max'], 'usd');
236
253
  if (usdRange) data.usdValue = usdRange;
237
254
 
238
255
  if (options['signature-hash']) {
@@ -606,9 +623,32 @@ USAGE:
606
623
  });
607
624
  }
608
625
 
609
- // Pagination (applied after filtering)
610
- if (options.offset) alerts = alerts.slice(Number(options.offset));
611
- if (options.limit) alerts = alerts.slice(0, Number(options.limit));
626
+ // Pagination (applied after filtering). Validate strictly rather than
627
+ // silently misbehaving on bad input:
628
+ // - `if (options.offset)` / `if (options.limit)` treat 0 as "not set"
629
+ // (falsy), so `--offset 0` / `--limit 0` were silently ignored
630
+ // instead of being honored.
631
+ // - `Number("abc")` is NaN, and `Array.prototype.slice` coerces a NaN
632
+ // argument to 0 — so `--offset abc` silently became a no-op and
633
+ // `--limit abc` silently returned zero results, with no error
634
+ // telling the caller their input wasn't a number at all.
635
+ // - Negative values (`--offset -1`) were accepted and fed straight
636
+ // into `slice()`, which treats negative indices as "from the end" —
637
+ // silently returning the wrong slice instead of rejecting the input.
638
+ if (options.offset !== undefined) {
639
+ const offset = Number(options.offset);
640
+ if (!Number.isInteger(offset) || offset < 0) {
641
+ throw new NansenError(`--offset must be a non-negative integer, got "${options.offset}"`, ErrorCode.INVALID_PARAMS);
642
+ }
643
+ alerts = alerts.slice(offset);
644
+ }
645
+ if (options.limit !== undefined) {
646
+ const limit = Number(options.limit);
647
+ if (!Number.isInteger(limit) || limit < 0) {
648
+ throw new NansenError(`--limit must be a non-negative integer, got "${options.limit}"`, ErrorCode.INVALID_PARAMS);
649
+ }
650
+ alerts = alerts.slice(0, limit);
651
+ }
612
652
 
613
653
  return alerts;
614
654
  },