nansen-cli 2.4.0 → 2.5.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/src/cli.js CHANGED
@@ -19,7 +19,7 @@ import { buildMcpCommands } from './commands/mcp.js';
19
19
  import { buildCompletionCommands } from './commands/completion.js';
20
20
  import { buildResearchCommands, RESEARCH_HISTORICAL_SUBCOMMANDS, RESEARCH_SUBCOMMANDS } from './commands/research.js';
21
21
  import { buildPagination, parseSort, parseCsvOption, rejectBlankOption, parseFiltersOption } from './query-options.js';
22
- import { resolveResearchCommand, validateResearchInput, validateOutputOptions, validateFieldSelection, unknownCommandError, normalizeFilterAddresses } from './input-validation.js';
22
+ import { resolveResearchCommand, validateResearchInput, UNAVAILABLE_COMMANDS, SUBCOMMAND_ALIASES, validateOutputOptions, validateFieldSelection, unknownCommandError, normalizeFilterAddresses } from './input-validation.js';
23
23
  import { enableAutoPagination, DEFAULT_MAX_PAGES, MAX_PAGES_LIMIT, locateRows } from './auto-paginate.js';
24
24
  export { buildPagination, parseSort };
25
25
  import { resolveAddress, isEnsName } from './ens.js';
@@ -32,6 +32,7 @@ import { collectCacheStats, clearCaches, formatCacheStats, formatCacheClear } fr
32
32
  import { creditWarning, noticeWarnings } from './response-meta.js';
33
33
  import { trackCommandSucceeded, trackCommandFailed, trackAuthCommand } from './telemetry.js';
34
34
  import { setDebugEnabled } from './debug.js';
35
+ import { telemetryFlagNames } from './telemetry-flags.js';
35
36
  import { createRequire } from 'module';
36
37
  import * as readline from 'readline';
37
38
 
@@ -224,7 +225,7 @@ export function compactSchema(schema) {
224
225
  // rather than swallowing the token after it.
225
226
  export const VALUELESS_FLAGS = new Set([
226
227
  'pretty', 'help', 'version', 'table', 'no-retry', 'cache', 'no-cache', 'stream',
227
- 'enrich', 'full', 'human', 'no-browser', 'api-key-stdin', 'enabled', 'disabled', 'expert', 'json', 'offline',
228
+ 'enrich', 'full', 'human', 'no-browser', 'api-key-stdin', 'webhook-secret-stdin', 'enabled', 'disabled', 'expert', 'json', 'offline',
228
229
  'no-simulate', 'no-verify-outcome', 'no-revoke-excessive-allowance', 'dry-run',
229
230
  'send-api-key', 'all', 'max', 'gasless', 'auto-slippage', 'unsafe-no-password',
230
231
  'reveal', 'yes', 'paginate', 'debug', 'new',
@@ -1283,7 +1284,9 @@ USAGE:
1283
1284
  nansen trade quote --chain <chain> --to-chain <chain> --from <token> --to <token> --amount <units>
1284
1285
  nansen trade execute --quote <quoteId> [--wallet <name>] [--dry-run] [--yes]
1285
1286
  nansen trade bridge-status --tx-hash <hash> --from-chain <chain> --to-chain <chain>
1286
- nansen trade limit-order <create|list|cancel|update> [options]
1287
+ nansen trade limit-order create [options] [--dry-run] [--yes]
1288
+ nansen trade limit-order cancel --order <orderId> [--dry-run] [--yes]
1289
+ nansen trade limit-order <list|update> [options]
1287
1290
 
1288
1291
  EXAMPLES:
1289
1292
  nansen trade quote --chain solana --from SOL --to USDC --amount 1000000000
@@ -1298,9 +1301,10 @@ WALLET:
1298
1301
  --wallet <name> Use a named wallet, or "walletconnect" / "wc" for WalletConnect.
1299
1302
  Defaults to the default local wallet if omitted.
1300
1303
 
1301
- BEFORE BROADCASTING (execute only):
1302
- --dry-run Validate and print what would be sent, then stop. Nothing is
1303
- signed or broadcast and the quote stays usable. Exits 0.
1304
+ BEFORE SIGNING (execute and limit-order create/cancel):
1305
+ --dry-run Print the execution or intent plan, then stop before signing
1306
+ or final submission. Limit-order preview makes no API request;
1307
+ cancel preview never requests its one-time transaction. Exits 0.
1304
1308
  --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1). The prompt
1305
1309
  only appears when stdin is a terminal — agents, CI and pipes run
1306
1310
  unprompted either way. Declining exits 1 with nothing signed.
@@ -2298,7 +2302,7 @@ export function buildCommands(deps = {}) {
2298
2302
  };
2299
2303
 
2300
2304
  // 'research' delegates to the category handlers defined above
2301
- const RESEARCH_CATEGORIES = new Set(['smart-money', 'profiler', 'token', 'search', 'perp', 'portfolio', 'points', 'prediction-market']);
2305
+ const RESEARCH_CATEGORIES = new Set(['smart-money', 'profiler', 'token', 'search', 'perp', 'portfolio', 'prediction-market']);
2302
2306
 
2303
2307
  // The analytics-only perp handler, captured before the trading wrapper below
2304
2308
  // replaces cmds['perp']. Both the wrapper and the research dispatch route to
@@ -2323,7 +2327,7 @@ export function buildCommands(deps = {}) {
2323
2327
  return researchSub(args, apiInstance, flags, options);
2324
2328
  }
2325
2329
  const category = RESEARCH_CATEGORY_ALIASES[rawCategory] || rawCategory;
2326
- if (!RESEARCH_CATEGORIES.has(category)) {
2330
+ if (!RESEARCH_CATEGORIES.has(category) && !UNAVAILABLE_COMMANDS.has(category)) {
2327
2331
  throw unknownCommandError('research category', rawCategory, [...RESEARCH_CATEGORIES, ...RESEARCH_SUBCOMMANDS]);
2328
2332
  }
2329
2333
  // `research perp` reaches only the analytics half (screener/leaderboard) —
@@ -2339,7 +2343,7 @@ export function buildCommands(deps = {}) {
2339
2343
  // 'trade' delegates to quote/execute from buildTradingCommands and limit-order from buildLimitOrderCommands
2340
2344
  const executionDeps = { ...deps, promptFn: confirmationPromptFn };
2341
2345
  const tradingCmds = buildTradingCommands(executionDeps);
2342
- const limitOrderCmds = buildLimitOrderCommands(deps);
2346
+ const limitOrderCmds = buildLimitOrderCommands(executionDeps);
2343
2347
  cmds['trade'] = async (args, apiInstance, flags, options) => {
2344
2348
  const sub = args[0];
2345
2349
  if (!sub || sub === 'help') {
@@ -2358,9 +2362,9 @@ SUBCOMMANDS:
2358
2362
  update Update trigger price or slippage
2359
2363
 
2360
2364
  USAGE:
2361
- nansen trade limit-order create --from <token> --to <token> --amount <units> --trigger-mint <token> --trigger-condition <above|below> --trigger-price <usd>
2365
+ nansen trade limit-order create --from <token> --to <token> --amount <units> --trigger-mint <token> --trigger-condition <above|below> --trigger-price <usd> [--dry-run] [--yes]
2362
2366
  nansen trade limit-order list [--state <active|past>]
2363
- nansen trade limit-order cancel --order <orderId>
2367
+ nansen trade limit-order cancel --order <orderId> [--dry-run] [--yes]
2364
2368
  nansen trade limit-order update --order <orderId> --trigger-price <usd>`);
2365
2369
  return;
2366
2370
  }
@@ -2411,7 +2415,7 @@ SUPPORTED ROUTES:
2411
2415
  // top of the pre-existing perp analytics command, so capture that handler and
2412
2416
  // keep screener/leaderboard reachable instead of shadowing them — both
2413
2417
  // `nansen perp screener` and `nansen research perp screener` route through here.
2414
- const perpCmds = buildPerpCommands(deps);
2418
+ const perpCmds = buildPerpCommands(executionDeps);
2415
2419
  const PERP_ANALYTICS_SUBCOMMANDS = new Set(['screener', 'leaderboard']);
2416
2420
  cmds['perp'] = async (args, apiInstance, flags, options) => {
2417
2421
  const sub = args[0];
@@ -2440,7 +2444,12 @@ USAGE:
2440
2444
  nansen perp transfer --direction spot-to-perp --amount 25
2441
2445
  nansen perp approve-builder-fee
2442
2446
  nansen perp positions
2443
- nansen perp account`);
2447
+ nansen perp account
2448
+
2449
+ BEFORE SUBMITTING (order, cancel, close, leverage):
2450
+ --dry-run Validate and print what would be submitted, then stop. Exits 0.
2451
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1). The prompt only
2452
+ appears when stdin is a terminal; declining exits 1, signing nothing.`);
2444
2453
  return;
2445
2454
  }
2446
2455
  if (!perpCmds[sub]) {
@@ -2460,6 +2469,31 @@ export const DEPRECATED_TO_RESEARCH = new Set(['smart-money', 'profiler', 'token
2460
2469
  // Subcommands that moved under 'trade'
2461
2470
  export const DEPRECATED_TO_TRADE = new Set(['quote', 'execute']);
2462
2471
 
2472
+ // Subcommands of removed commands (UNAVAILABLE_COMMANDS), which have no schema entry.
2473
+ const REMOVED_SUBCOMMANDS = { points: ['leaderboard'] };
2474
+
2475
+ /**
2476
+ * Command name for telemetry. Positionals are often values (a search query,
2477
+ * an address), so only subcommands listed in the schema are kept.
2478
+ */
2479
+ function telemetryCommandName(commands, command, subcommand) {
2480
+ if (!Object.hasOwn(commands, command)) return 'unknown';
2481
+ if (!subcommand) return command;
2482
+ if (command === 'research') {
2483
+ const category = RESEARCH_CATEGORY_ALIASES[subcommand] || subcommand;
2484
+ const known = Object.hasOwn(SCHEMA.commands.research.subcommands, category) || UNAVAILABLE_COMMANDS.has(category);
2485
+ return known ? `research ${category}` : 'research';
2486
+ }
2487
+ // `perp` is both a top-level command and a research category (screener, leaderboard).
2488
+ const known = [SCHEMA.commands[command]?.subcommands, SCHEMA.commands.research.subcommands[command]?.subcommands];
2489
+ if (known.some(subcommands => subcommands && Object.hasOwn(subcommands, subcommand))
2490
+ || REMOVED_SUBCOMMANDS[command]?.includes(subcommand)
2491
+ || Object.hasOwn(SUBCOMMAND_ALIASES[command] ?? {}, subcommand)) {
2492
+ return `${command} ${subcommand}`;
2493
+ }
2494
+ return command;
2495
+ }
2496
+
2463
2497
  // Command aliases: top-level shortcuts that resolve before routing
2464
2498
  export const COMMAND_ALIASES = {
2465
2499
  'tgm': 'token', // Token God Mode
@@ -2591,9 +2625,10 @@ function emitResponseMetadata(api, errorOutput) {
2591
2625
  // An aggregate belongs to the primary paginated endpoint even if a composite
2592
2626
  // handler made auxiliary requests afterward and changed lastEndpoint.
2593
2627
  const endpoint = api.paginatedResponseMeta ? api.paginatedEndpoint : api.lastEndpoint;
2594
- // A cache hit records no response meta; with no live call at all there is
2595
- // nothing to estimate.
2596
- if (!responseMeta && api.servedFromCache === true) {
2628
+ // Cached advisories can supply metadata without any live accounting.
2629
+ // With no live call at all there is nothing to estimate.
2630
+ if (api.servedFromCache === true && !api.paginatedResponseMeta
2631
+ && (!responseMeta || (!responseMeta.credits && !api.lastEndpoint))) {
2597
2632
  errorOutput('Credits: 0 (cached)');
2598
2633
  return;
2599
2634
  }
@@ -2697,12 +2732,17 @@ export async function runCLI(rawArgs, deps = {}) {
2697
2732
  // recreate update/telemetry state during the same invocation.
2698
2733
  const isMcpUsage = command === 'mcp' && (subcommand !== 'verify' || flags.help || flags.h);
2699
2734
  const isAuthMutation = command === 'login' || command === 'logout';
2735
+ const isOfflineLimitOrderDryRun = command === 'trade'
2736
+ && subArgs[0] === 'limit-order'
2737
+ && (subArgs[1] === 'create' || subArgs[1] === 'cancel')
2738
+ && flags['dry-run'] === true;
2700
2739
  const isOfflineCommand = command === 'auth'
2701
2740
  || (command === 'doctor' && flags.offline)
2702
2741
  || isMcpUsage
2703
2742
  || command === 'completion'
2704
2743
  || command === 'cache'
2705
- || (command === 'feedback' && subcommand === 'forget');
2744
+ || (command === 'feedback' && subcommand === 'forget')
2745
+ || isOfflineLimitOrderDryRun;
2706
2746
  const trackSucceeded = isOfflineCommand ? async () => {} : isAuthMutation ? metadata => trackAuthCommand({ ...metadata, command }) : trackCommandSucceeded;
2707
2747
  const trackFailed = isOfflineCommand ? async () => {} : isAuthMutation ? metadata => trackAuthCommand({ ...metadata, command, failed: true }) : trackCommandFailed;
2708
2748
 
@@ -2735,7 +2775,11 @@ export async function runCLI(rawArgs, deps = {}) {
2735
2775
  return { type: 'version', data: VERSION };
2736
2776
  }
2737
2777
 
2738
- if (command === 'help' || flags.help || flags.h) {
2778
+ // A removed command has no help to show: let its handler answer --help with
2779
+ // the same COMMAND_UNAVAILABLE error, rather than printing a generic listing.
2780
+ const unavailableCommand = UNAVAILABLE_COMMANDS.has(command)
2781
+ || (command === 'research' && UNAVAILABLE_COMMANDS.has(RESEARCH_CATEGORY_ALIASES[subcommand] || subcommand));
2782
+ if (command === 'help' || ((flags.help || flags.h) && !unavailableCommand)) {
2739
2783
  // Help for an offline command still owes the zero-network contract: the
2740
2784
  // cost-map refresh fetches the OpenAPI spec and writes ~/.nansen/cost-map.json.
2741
2785
  if (!isOfflineCommand && !isAuthMutation) await refreshCostMapIfStale();
@@ -2850,9 +2894,13 @@ export async function runCLI(rawArgs, deps = {}) {
2850
2894
  // ── Telemetry setup ──
2851
2895
  const startTime = Date.now();
2852
2896
  const fullCommand = subcommand ? `${command} ${subcommand}` : command;
2897
+ const telemetryCommand = telemetryCommandName(commands, command, subcommand);
2853
2898
  const flagNames = Object.keys(flags).filter(k => flags[k]).map(k => `--${k}`);
2854
2899
  const optionNames = Object.keys(options).map(k => `--${k}`);
2855
- const usedFlags = [...flagNames, ...optionNames];
2900
+ // Only names the CLI defines reach telemetry (login/logout keep their own set).
2901
+ const usedFlags = isAuthMutation
2902
+ ? [...flagNames, ...optionNames]
2903
+ : telemetryFlagNames({ schema: SCHEMA, command, subArgs, switches: VALUELESS_FLAGS }, [...flagNames, ...optionNames]);
2856
2904
  const chain = options.chain || null;
2857
2905
 
2858
2906
  if (!commands[command]) {
@@ -2861,7 +2909,7 @@ export async function runCLI(rawArgs, deps = {}) {
2861
2909
  // or an unquoted shell variable under zsh (which, unlike bash, does not
2862
2910
  // word-split `$var`). Point the user straight at the cause instead of a bare
2863
2911
  // "Unknown command" that reads like a spurious failure.
2864
- const available = Object.keys(commands);
2912
+ const available = Object.keys(commands).filter(name => !UNAVAILABLE_COMMANDS.has(name));
2865
2913
  const error = /\s/.test(command)
2866
2914
  ? new NansenError(
2867
2915
  `Unknown command: "${command}". This looks like multiple words passed as one argument — check your shell quoting (use \`nansen trade --help\`, not \`nansen "trade --help"\`).`,
@@ -2871,7 +2919,7 @@ export async function runCLI(rawArgs, deps = {}) {
2871
2919
  const errorData = formatError(error);
2872
2920
  const formatted = formatOutput(errorData, { pretty, table, csv });
2873
2921
  output(formatted.text);
2874
- await trackFailed({ command: fullCommand, duration_ms: Date.now() - startTime, error_code: ErrorCode.UNKNOWN_COMMAND, flags: usedFlags, chain });
2922
+ await trackFailed({ command: telemetryCommand, duration_ms: Date.now() - startTime, error_code: ErrorCode.UNKNOWN_COMMAND, flags: usedFlags, chain });
2875
2923
  exit(1);
2876
2924
  return { type: 'error', data: errorData };
2877
2925
  }
@@ -2907,11 +2955,16 @@ export async function runCLI(rawArgs, deps = {}) {
2907
2955
  if (options['x402-payment-signature']) {
2908
2956
  defaultHeaders['Payment-Signature'] = options['x402-payment-signature'];
2909
2957
  }
2910
- api = new NansenAPIClass(undefined, undefined, { retry: retryOptions, cache: cacheOptions, defaultHeaders, authState: inputInteractiveDeps.authState });
2958
+ // Limit-order dry runs are intentionally local previews. In addition to
2959
+ // suppressing update checks and telemetry above, avoid constructing the API
2960
+ // client because its constructor resolves saved Nansen credentials.
2961
+ if (!isOfflineLimitOrderDryRun) {
2962
+ api = new NansenAPIClass(undefined, undefined, { retry: retryOptions, cache: cacheOptions, defaultHeaders, authState: inputInteractiveDeps.authState });
2963
+ }
2911
2964
 
2912
2965
  // --all aliases --paginate; wrapping api.request gives every list handler
2913
2966
  // the same max-pages bound while leaving non-list requests untouched.
2914
- if (flags.paginate || flags.all) {
2967
+ if ((flags.paginate || flags.all) && api) {
2915
2968
  const maxPages = parsePositiveSafeIntegerOption(
2916
2969
  'max-pages', options, flags, DEFAULT_MAX_PAGES, { max: MAX_PAGES_LIMIT },
2917
2970
  );
@@ -2939,7 +2992,13 @@ export async function runCLI(rawArgs, deps = {}) {
2939
2992
  // on the instance next to the cache-hit early return in request(), so it
2940
2993
  // survives that reshaping. Compared against `true` so a stubbed API whose
2941
2994
  // every property is a mock function doesn't read as a hit.
2942
- const fromCache = !!result?._meta?.fromCache || api.servedFromCache === true;
2995
+ //
2996
+ // A --paginate result mixes pages, and both of those describe a single
2997
+ // page; it was served from the cache only if no page went to the API.
2998
+ const paginatedPages = api?.paginatedResponseMeta?.pagination;
2999
+ const fromCache = paginatedPages
3000
+ ? paginatedPages.livePages === 0
3001
+ : !!result?._meta?.fromCache || api?.servedFromCache === true;
2943
3002
 
2944
3003
  // Credit balance warning, from the headers on the call just made. Goes to
2945
3004
  // stderr so it never contaminates the JSON on stdout that agents parse.
@@ -2949,14 +3008,14 @@ export async function runCLI(rawArgs, deps = {}) {
2949
3008
 
2950
3009
  // Commands that handle their own output return undefined
2951
3010
  if (result === undefined) {
2952
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, flags: usedFlags, chain });
3011
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, flags: usedFlags, chain });
2953
3012
  return { type: 'no-output', command };
2954
3013
  }
2955
3014
 
2956
3015
  // Feedback JSON is a complete receipt, even alongside list-format flags.
2957
3016
  if (command === 'feedback') {
2958
3017
  output(formatOutput({ success: true, data: result }, { pretty }).text);
2959
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: false, flags: usedFlags, chain });
3018
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, from_cache: false, flags: usedFlags, chain });
2960
3019
  return { type: 'success', data: result };
2961
3020
  }
2962
3021
 
@@ -2964,7 +3023,7 @@ export async function runCLI(rawArgs, deps = {}) {
2964
3023
  if (command === 'schema') {
2965
3024
  const formatted = formatOutput(result, { pretty, table: false });
2966
3025
  output(formatted.text);
2967
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, flags: usedFlags, chain });
3026
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, flags: usedFlags, chain });
2968
3027
  return { type: 'schema', data: result };
2969
3028
  }
2970
3029
 
@@ -2982,7 +3041,7 @@ export async function runCLI(rawArgs, deps = {}) {
2982
3041
  // Alerts list with --table uses custom table format
2983
3042
  if (command === 'alerts' && subcommand === 'list' && table) {
2984
3043
  output(formatAlertsTable(result));
2985
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
3044
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
2986
3045
  return { type: 'success', data: result };
2987
3046
  }
2988
3047
 
@@ -2993,14 +3052,14 @@ export async function runCLI(rawArgs, deps = {}) {
2993
3052
  if (streamOutput) {
2994
3053
  output(streamOutput);
2995
3054
  }
2996
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
3055
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
2997
3056
  return { type: 'stream', data: result };
2998
3057
  }
2999
3058
 
3000
3059
  const successData = { success: true, data: result };
3001
3060
  const formatted = formatOutput(successData, { pretty, table, csv });
3002
3061
  output(formatted.text);
3003
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
3062
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
3004
3063
  return { type: csv ? 'csv' : 'success', data: result };
3005
3064
  } catch (error) {
3006
3065
  // A failed later page can still have incurred charges on earlier pages.
@@ -3026,7 +3085,7 @@ export async function runCLI(rawArgs, deps = {}) {
3026
3085
  output(formatted.text);
3027
3086
  }
3028
3087
  await trackFailed({
3029
- command: fullCommand,
3088
+ command: telemetryCommand,
3030
3089
  duration_ms: Date.now() - startTime,
3031
3090
  error_code: error.code || 'UNKNOWN',
3032
3091
  status: error.status || null,
@@ -6,6 +6,55 @@
6
6
  import { NansenError, ErrorCode } from '../api.js';
7
7
  import { parseCsvOption } from '../query-options.js';
8
8
  import { unknownCommandError } from '../input-validation.js';
9
+ import { hasControlChars, readWebhookSecretInput } from '../auth-key-input.js';
10
+
11
+ // ============= Webhook signing secret input =============
12
+
13
+ /** Environment variable read for the webhook signing secret. */
14
+ export const WEBHOOK_SECRET_ENV = 'NANSEN_WEBHOOK_SECRET';
15
+
16
+ /**
17
+ * Resolve the webhook signing secret for create/update, or undefined.
18
+ *
19
+ * Sources, in order: --webhook-secret <secret> or --webhook-secret-stdin
20
+ * (passing both is an error), then NANSEN_WEBHOOK_SECRET. An explicit option
21
+ * overrides the environment, as --api-key overrides NANSEN_API_KEY. The
22
+ * environment is read only together with --webhook, so a variable exported for
23
+ * other commands never adds a secret to an alert that has no webhook channel.
24
+ * Errors never quote the secret.
25
+ */
26
+ export async function resolveWebhookSecret(options, flags, { env = process.env, stdin = process.stdin, stdinTTY } = {}) {
27
+ // A bare `--webhook-secret` (no value) lands in flags, possibly as
28
+ // `[true, true]` when repeated; any presence counts as the flag being given.
29
+ const bareFlag = flags['webhook-secret'] !== undefined;
30
+ const fromFlag = Object.hasOwn(options, 'webhook-secret') || bareFlag;
31
+ const fromStdin = flags['webhook-secret-stdin'] !== undefined;
32
+ if (fromFlag && fromStdin) {
33
+ throw new NansenError('Use either --webhook-secret or --webhook-secret-stdin, not both.', ErrorCode.INVALID_PARAMS);
34
+ }
35
+ if (fromFlag) {
36
+ if (bareFlag && Object.hasOwn(options, 'webhook-secret')) {
37
+ throw new NansenError('--webhook-secret can only be passed once', ErrorCode.INVALID_PARAMS);
38
+ }
39
+ if (bareFlag) {
40
+ throw new NansenError('--webhook-secret requires a value. To keep the secret out of shell history, use --webhook-secret-stdin or NANSEN_WEBHOOK_SECRET instead.', ErrorCode.MISSING_PARAM);
41
+ }
42
+ if (!options.webhook) throw new NansenError('--webhook-secret requires --webhook', ErrorCode.INVALID_PARAMS);
43
+ return { value: options['webhook-secret'], source: '--webhook-secret' };
44
+ }
45
+ if (fromStdin) {
46
+ if (!options.webhook) throw new NansenError('--webhook-secret-stdin requires --webhook', ErrorCode.INVALID_PARAMS);
47
+ const value = await readWebhookSecretInput(stdin, stdinTTY ?? stdin?.isTTY);
48
+ return { value, source: '--webhook-secret-stdin' };
49
+ }
50
+ const value = typeof env?.[WEBHOOK_SECRET_ENV] === 'string' ? env[WEBHOOK_SECRET_ENV].trim() : '';
51
+ if (!value || !options.webhook) return undefined;
52
+ // Same rule as stdin: a line break means more than one value.
53
+ if (hasControlChars(value)) {
54
+ throw new NansenError(`${WEBHOOK_SECRET_ENV} must be a single line without control characters.`, ErrorCode.INVALID_PARAMS);
55
+ }
56
+ return { value, source: WEBHOOK_SECRET_ENV };
57
+ }
9
58
 
10
59
  // ============= Channel secret redaction =============
11
60
 
@@ -707,7 +756,7 @@ const TIME_WINDOW_BY_TYPE = {
707
756
  };
708
757
 
709
758
  export function buildAlertsCommands(deps = {}) {
710
- const { log = console.log } = deps;
759
+ const { log = console.log, env = process.env, stdin = process.stdin, stdinTTY } = deps;
711
760
 
712
761
  return {
713
762
  'alerts': async (args, apiInstance, flags, options) => {
@@ -762,7 +811,9 @@ REQUIRED:
762
811
 
763
812
  OPTIONS (all types):
764
813
  --chains <chains> Comma-separated chains (e.g. ethereum,solana)
765
- --webhook-secret <secret> Signing secret for webhook payload verification (webhook only)
814
+ --webhook-secret-stdin Read the webhook signing secret from a pipe or file (webhook only)
815
+ --webhook-secret <secret> Signing secret on the command line (visible in shell history and
816
+ the process list; prefer --webhook-secret-stdin or NANSEN_WEBHOOK_SECRET)
766
817
  --token <address:chain> Include token (repeatable)
767
818
  --exclude-token <addr:chain> Exclude token (repeatable)
768
819
  --description '<text>' Alert description
@@ -800,7 +851,15 @@ NOTE: Use single quotes for names with $ or special chars: --name 'SM >$1M'
800
851
  EXAMPLES:
801
852
  nansen alerts create --name 'ETH SM Inflow' --type sm-token-flows --chains ethereum --telegram 5238612255 --inflow-1h-min 1000000
802
853
  nansen alerts create --name 'USDC Transfers' --type common-token-transfer --chains ethereum --telegram 5238612255 --events send,receive --usd-min 1000000 --subject label:"Centralized Exchange"
803
- nansen alerts create --name 'Contract Calls' --type smart-contract-call --chains ethereum --telegram 5238612255 --signature-hash 0xa9059cbb --caller address:0xabc`,
854
+ nansen alerts create --name 'Contract Calls' --type smart-contract-call --chains ethereum --telegram 5238612255 --signature-hash 0xa9059cbb --caller address:0xabc
855
+ nansen alerts create --name 'Hook' --type sm-token-flows --chains ethereum --webhook https://example.com/hook --inflow-1h-min 1000000 --webhook-secret-stdin < secret.txt
856
+
857
+ WEBHOOK SIGNING SECRET (minimum 16 characters, webhook only):
858
+ --webhook-secret-stdin Pipe or redirect it: ... --webhook-secret-stdin < secret.txt
859
+ NANSEN_WEBHOOK_SECRET Environment variable, read only when --webhook is given
860
+ --webhook-secret <secret> Still accepted, but it lands in shell history and the process list
861
+ --webhook-secret and --webhook-secret-stdin cannot be combined. Either one overrides
862
+ NANSEN_WEBHOOK_SECRET. The secret is redacted in output and errors unless --reveal is passed.`,
804
863
 
805
864
  update: `nansen alerts update — Update an existing alert
806
865
 
@@ -816,7 +875,8 @@ NOTE: --type cannot change an existing alert's type (use delete + create instead
816
875
  EXAMPLES:
817
876
  nansen alerts update abc123 --name 'New Name'
818
877
  nansen alerts update abc123 --inflow-1h-min 2000000
819
- nansen alerts update abc123 --chains ethereum,base --inflow-1h-min 2000000`,
878
+ nansen alerts update abc123 --chains ethereum,base --inflow-1h-min 2000000
879
+ nansen alerts update abc123 --webhook https://example.com/hook --webhook-secret-stdin < secret.txt`,
820
880
 
821
881
  toggle: `nansen alerts toggle — Enable or disable an alert
822
882
 
@@ -838,11 +898,12 @@ USAGE:
838
898
  return;
839
899
  }
840
900
 
901
+ // Signing secret resolved once from --webhook-secret, --webhook-secret-stdin
902
+ // or NANSEN_WEBHOOK_SECRET before create/update runs (stdin can only be read once).
903
+ let webhookSecret;
904
+
841
905
  // Build channels array from --telegram/--slack/--discord/--webhook flags
842
906
  function buildChannels() {
843
- if (options["webhook-secret"] && !options.webhook) {
844
- throw new NansenError('--webhook-secret requires --webhook', ErrorCode.INVALID_PARAMS);
845
- }
846
907
  for (const flag of ['slack', 'discord', 'webhook', 'webhook-secret']) {
847
908
  if (Array.isArray(options[flag])) {
848
909
  throw new NansenError(`--${flag} can only be passed once`, ErrorCode.INVALID_PARAMS);
@@ -858,11 +919,25 @@ USAGE:
858
919
  if (options.telegram) channels.push({ type: 'telegram', data: { chatId: String(options.telegram) } });
859
920
  if (options.slack) channels.push({ type: 'slack', data: { webhookUrl: options.slack } });
860
921
  if (options.discord) channels.push({ type: 'discord', data: { webhookUrl: options.discord } });
922
+ // Output masks a secret as a whole (REDACTED), so only an all-asterisk
923
+ // value is a pasted-back redaction; a real secret may contain `****`.
924
+ if (webhookSecret && webhookSecret.source !== '--webhook-secret' && /^\*+$/.test(webhookSecret.value)) {
925
+ throw new NansenError(
926
+ `The webhook secret from ${webhookSecret.source} looks like a redacted value from alerts output. Pass the full value (nansen alerts list --reveal shows it).`,
927
+ ErrorCode.INVALID_PARAMS,
928
+ );
929
+ }
861
930
  if (options.webhook) {
862
931
  const webhookData = { webhookUrl: options.webhook };
863
- if (options["webhook-secret"]) {
864
- if (options["webhook-secret"].length < 16) throw new NansenError('--webhook-secret must be at least 16 characters', ErrorCode.INVALID_PARAMS);
865
- webhookData.secret = options["webhook-secret"];
932
+ if (webhookSecret) {
933
+ const { value, source } = webhookSecret;
934
+ if (typeof value !== 'string' || value.length < 16) {
935
+ throw new NansenError(
936
+ source === '--webhook-secret' ? '--webhook-secret must be at least 16 characters' : `The webhook secret from ${source} must be at least 16 characters`,
937
+ ErrorCode.INVALID_PARAMS,
938
+ );
939
+ }
940
+ webhookData.secret = value;
866
941
  }
867
942
  channels.push({ type: 'webhook', data: webhookData });
868
943
  }
@@ -1019,6 +1094,9 @@ USAGE:
1019
1094
  }
1020
1095
 
1021
1096
  try {
1097
+ if (sub === 'create' || sub === 'update') {
1098
+ webhookSecret = await resolveWebhookSecret(options, flags, { env, stdin, stdinTTY });
1099
+ }
1022
1100
  const result = await handlers[sub]();
1023
1101
  return flags.reveal ? result : redactAlertSecrets(result);
1024
1102
  } catch (err) {
@@ -1046,7 +1124,8 @@ USAGE:
1046
1124
  // API error bodies (message and details) can echo the submitted channels,
1047
1125
  // and the hint above quotes the webhook URL; all are masked here unless
1048
1126
  // --reveal is passed.
1049
- throw flags.reveal ? error : redactAlertError(error, options, sentPayload);
1127
+ const redactOptions = webhookSecret ? { ...options, 'webhook-secret': webhookSecret.value } : options;
1128
+ throw flags.reveal ? error : redactAlertError(error, redactOptions, sentPayload);
1050
1129
  }
1051
1130
  },
1052
1131
  };
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import { CommandError } from '../api.js';
13
+ import { UNAVAILABLE_COMMANDS } from '../input-validation.js';
13
14
  import { createRequire } from 'module';
14
15
 
15
16
  const require = createRequire(import.meta.url);
@@ -41,7 +42,9 @@ export const UNSCHEMA_COMMANDS = {
41
42
  * teaches the spelling we are trying to retire.
42
43
  */
43
44
  export const EXCLUDED_COMMANDS = new Set([
44
- 'smart-money', 'profiler', 'token', 'search', 'portfolio', 'points', 'prediction-market',
45
+ 'smart-money', 'profiler', 'token', 'search', 'portfolio', 'prediction-market',
46
+ // Removed commands that still answer COMMAND_UNAVAILABLE.
47
+ ...UNAVAILABLE_COMMANDS,
45
48
  'quote', 'execute',
46
49
  // Undocumented top-level alias of `trade bridge-status`: reachable because
47
50
  // runCLI spreads buildTradingCommands over the root, absent from HELP.
package/src/ens.js CHANGED
@@ -4,9 +4,11 @@
4
4
  * Zero external dependencies.
5
5
  */
6
6
 
7
+ import http from 'http';
7
8
  import https from 'https';
8
9
  import { keccak256 } from './crypto.js';
9
10
  import { EVM_CHAINS } from './chain-ids.js';
11
+ import { CHAIN_RPCS } from './rpc-urls.js';
10
12
 
11
13
  const ENS_PATTERN = /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.eth$/;
12
14
 
@@ -84,9 +86,13 @@ function httpsPost(url, body, timeoutMs = 5000) {
84
86
  return new Promise((resolve, reject) => {
85
87
  const payload = JSON.stringify(body);
86
88
  const parsed = new URL(url);
87
- const req = https.request({
89
+ // The URL can come from NANSEN_EVM_RPC, so keep its port and query string
90
+ // (some providers put the key in `?key=`) and allow a plain-http local node.
91
+ const client = parsed.protocol === 'http:' ? http : https;
92
+ const req = client.request({
88
93
  hostname: parsed.hostname,
89
- path: parsed.pathname,
94
+ port: parsed.port || undefined,
95
+ path: parsed.pathname + parsed.search,
90
96
  method: 'POST',
91
97
  timeout: timeoutMs,
92
98
  headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) }
@@ -130,13 +136,16 @@ function namehash(name) {
130
136
 
131
137
  const ENS_REGISTRY = '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e';
132
138
  const ZERO_HASH = '0000000000000000000000000000000000000000000000000000000000000000';
133
- const RPC_URL = 'https://eth.llamarpc.com';
134
139
 
135
140
  async function resolveOnchain(name) {
136
141
  const hash = namehash(name);
142
+ // Same Ethereum RPC as every other command (NANSEN_EVM_RPC or the shared
143
+ // default). The fallback used to be pinned to eth.llamarpc.com, which now
144
+ // answers HTTP 525, and could not be pointed anywhere else.
145
+ const rpcUrl = CHAIN_RPCS.ethereum;
137
146
 
138
147
  // Step 1: Get resolver from ENS registry — resolver(bytes32)
139
- const resolverResult = await httpsPost(RPC_URL, {
148
+ const resolverResult = await httpsPost(rpcUrl, {
140
149
  jsonrpc: '2.0', id: 1, method: 'eth_call',
141
150
  params: [{ to: ENS_REGISTRY, data: '0x0178b8bf' + hash }, 'latest']
142
151
  });
@@ -147,7 +156,7 @@ async function resolveOnchain(name) {
147
156
  const resolver = '0x' + resolverHex.slice(26);
148
157
 
149
158
  // Step 2: Call addr(bytes32) on the resolver — selector 0x3b3b57de
150
- const addrResult = await httpsPost(RPC_URL, {
159
+ const addrResult = await httpsPost(rpcUrl, {
151
160
  jsonrpc: '2.0', id: 2, method: 'eth_call',
152
161
  params: [{ to: resolver, data: '0x3b3b57de' + hash }, 'latest']
153
162
  });
@@ -37,6 +37,7 @@ export const ERROR_CODES = {
37
37
  // ── Input and validation ──
38
38
  INVALID_PARAMS: { group: 'input', description: 'An option or request field has an invalid value, or the command does not accept it. `details.errors[]` names each field.' },
39
39
  MISSING_PARAM: { group: 'input', description: 'A required option or request field is missing. `details.errors[]` names each field.' },
40
+ NOT_A_PIPE: { group: 'input', description: 'An option that reads a secret from stdin (`--api-key-stdin`, `--webhook-secret-stdin`) was used with a terminal on stdin. Pipe the value or redirect a file.' },
40
41
  MISSING_ARGS: { group: 'input', description: 'A trade or wallet command is missing required arguments; the message shows the usage.' },
41
42
  INVALID_INPUT: { group: 'input', description: 'A trade, bridge, perp or wallet argument failed local validation.' },
42
43
  INVALID_ADDRESS: { group: 'input', description: 'An address does not match the format of the selected chain.' },
@@ -183,6 +184,7 @@ export const ERROR_CODES = {
183
184
  BUILDER_FEE_TOO_HIGH: { group: 'perp', description: 'The builder fee is above the allowed ceiling.' },
184
185
  BUILDER_FEE_UNAVAILABLE: { group: 'perp', description: 'The builder fee could not be read or approved.' },
185
186
  META_UNAVAILABLE: { group: 'perp', description: 'Hyperliquid asset metadata is not available.', retry: true },
187
+ NO_OPEN_POSITION: { group: 'perp', description: 'perp close --dry-run found no open position in that coin, so a real close would be rejected. The positions data can lag a fill that just happened, so retry after a few seconds if the position was opened moments ago.', retry: true },
186
188
  SANCTIONED: { group: 'perp', description: 'The address failed sanctions screening.' },
187
189
  SCREENING_UNAVAILABLE: { group: 'perp', description: 'Sanctions screening is not available, so the action was refused.', retry: true },
188
190
  UNSUPPORTED_NETWORK: { group: 'perp', description: 'The network is not supported for this perp action.' },
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * Acknowledgement gate shared by the commands that move funds on-chain
3
- * (`trade execute`, `bridge execute`).
3
+ * (`trade execute`, `bridge execute`, `trade limit-order create`/`cancel`) and
4
+ * the perp commands that change Hyperliquid state (`perp order`, `close`,
5
+ * `cancel`, `leverage`).
4
6
  *
5
7
  * Two independent switches, both resolved in the command layer:
6
8
  * --dry-run run the validation the command normally runs, print the plan,
@@ -72,11 +74,14 @@ export async function guardExecution({
72
74
  log = () => {},
73
75
  confirmationLog = log,
74
76
  question = 'Broadcast this transaction? [y/N] ',
77
+ dryRunNotice = [
78
+ '\n DRY RUN — nothing was broadcast. No transaction was signed and the quote was not consumed.',
79
+ ' Re-run without --dry-run to sign and broadcast it.\n',
80
+ ],
75
81
  }) {
76
82
  if (dryRun) {
77
83
  log(plan);
78
- log('\n DRY RUN — nothing was broadcast. No transaction was signed and the quote was not consumed.');
79
- log(' Re-run without --dry-run to sign and broadcast it.\n');
84
+ for (const line of dryRunNotice) log(line);
80
85
  return false;
81
86
  }
82
87
 
@@ -126,9 +126,13 @@ const CATEGORY_ALIASES = { tgm: 'token', sm: 'smart-money', prof: 'profiler', po
126
126
  // Categories that still run without the `research` prefix.
127
127
  const TOP_LEVEL_CATEGORIES = new Set(['smart-money', 'profiler', 'token', 'search', 'portfolio', 'prediction-market']);
128
128
  // Subcommand spellings a handler accepts besides the schema name.
129
- const SUBCOMMAND_ALIASES = { portfolio: { 'defi-holdings': 'defi' } };
130
- // Categories whose handler does its own routing and never calls the API.
131
- const UNVALIDATED_CATEGORIES = new Set(['points']);
129
+ export const SUBCOMMAND_ALIASES = { portfolio: { 'defi-holdings': 'defi' } };
130
+ // Commands whose endpoint was removed. Their handler still answers with
131
+ // COMMAND_UNAVAILABLE, both as `nansen <name>` and `nansen research <name>`,
132
+ // but they are left out of the schema, help listings, completions and "did
133
+ // you mean" suggestions so agents do not spend a call on them. Validation
134
+ // skips them, since the schema no longer has an entry to check against.
135
+ export const UNAVAILABLE_COMMANDS = new Set(['points']);
132
136
 
133
137
  /**
134
138
  * The research schema entry a command line runs, or null when the command is
@@ -147,6 +151,7 @@ export function resolveResearchCommand(schema, command, subArgs) {
147
151
  const raw = subArgs[0];
148
152
  if (!raw || raw === 'help') return null;
149
153
  category = Object.hasOwn(CATEGORY_ALIASES, raw) ? CATEGORY_ALIASES[raw] : raw;
154
+ if (UNAVAILABLE_COMMANDS.has(category)) return null;
150
155
  if (!Object.hasOwn(research, category)) {
151
156
  throw unknownCommandError('research category', raw, Object.keys(research));
152
157
  }
@@ -163,7 +168,6 @@ export function resolveResearchCommand(schema, command, subArgs) {
163
168
  } else {
164
169
  return null;
165
170
  }
166
- if (UNVALIDATED_CATEGORIES.has(category)) return null;
167
171
 
168
172
  const entry = research[category];
169
173
  if (!entry.subcommands) {