nansen-cli 2.4.0 → 2.6.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.
@@ -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) => {
@@ -732,7 +781,7 @@ Run: nansen alerts <subcommand> --help`,
732
781
  list: `nansen alerts list — List all alerts
733
782
 
734
783
  USAGE:
735
- nansen alerts list [--table] [--pretty] [--type <type>] [--enabled|--disabled] [--token-address <addr>] [--chain <chain>] [--limit <n>] [--offset <n>] [--reveal]
784
+ nansen alerts list [--table] [--pretty] [--type <type>] [--enabled|--disabled] [--token <addr>] [--chain <chain>] [--limit <n>] [--offset <n>] [--reveal]
736
785
 
737
786
  OPTIONS:
738
787
  --table Human-readable table output (columns: ID, NAME, TYPE, ENABLED, CHANNELS)
@@ -740,7 +789,7 @@ OPTIONS:
740
789
  --reveal Show full channel webhook URLs and secrets (redacted by default)
741
790
  --type <type> Filter by alert type (sm-token-flows, common-token-transfer, smart-contract-call)
742
791
  --enabled / --disabled Filter by enabled state
743
- --token-address <addr> Filter by token address
792
+ --token <addr> Filter by token address (alias --token-address)
744
793
  --chain <chain> Filter by chain
745
794
  --limit <n> Max results
746
795
  --offset <n> Skip first N results
@@ -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
 
@@ -830,7 +890,10 @@ OPTIONS:
830
890
  delete: `nansen alerts delete — Delete an alert
831
891
 
832
892
  USAGE:
833
- nansen alerts delete <id>`,
893
+ nansen alerts delete <id>
894
+
895
+ OPTIONS:
896
+ --reveal Show full channel URLs and secrets in the response (redacted by default)`,
834
897
  };
835
898
 
836
899
  if (!sub || sub === 'help') {
@@ -838,11 +901,12 @@ USAGE:
838
901
  return;
839
902
  }
840
903
 
904
+ // Signing secret resolved once from --webhook-secret, --webhook-secret-stdin
905
+ // or NANSEN_WEBHOOK_SECRET before create/update runs (stdin can only be read once).
906
+ let webhookSecret;
907
+
841
908
  // Build channels array from --telegram/--slack/--discord/--webhook flags
842
909
  function buildChannels() {
843
- if (options["webhook-secret"] && !options.webhook) {
844
- throw new NansenError('--webhook-secret requires --webhook', ErrorCode.INVALID_PARAMS);
845
- }
846
910
  for (const flag of ['slack', 'discord', 'webhook', 'webhook-secret']) {
847
911
  if (Array.isArray(options[flag])) {
848
912
  throw new NansenError(`--${flag} can only be passed once`, ErrorCode.INVALID_PARAMS);
@@ -858,11 +922,25 @@ USAGE:
858
922
  if (options.telegram) channels.push({ type: 'telegram', data: { chatId: String(options.telegram) } });
859
923
  if (options.slack) channels.push({ type: 'slack', data: { webhookUrl: options.slack } });
860
924
  if (options.discord) channels.push({ type: 'discord', data: { webhookUrl: options.discord } });
925
+ // Output masks a secret as a whole (REDACTED), so only an all-asterisk
926
+ // value is a pasted-back redaction; a real secret may contain `****`.
927
+ if (webhookSecret && webhookSecret.source !== '--webhook-secret' && /^\*+$/.test(webhookSecret.value)) {
928
+ throw new NansenError(
929
+ `The webhook secret from ${webhookSecret.source} looks like a redacted value from alerts output. Pass the full value (nansen alerts list --reveal shows it).`,
930
+ ErrorCode.INVALID_PARAMS,
931
+ );
932
+ }
861
933
  if (options.webhook) {
862
934
  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"];
935
+ if (webhookSecret) {
936
+ const { value, source } = webhookSecret;
937
+ if (typeof value !== 'string' || value.length < 16) {
938
+ throw new NansenError(
939
+ source === '--webhook-secret' ? '--webhook-secret must be at least 16 characters' : `The webhook secret from ${source} must be at least 16 characters`,
940
+ ErrorCode.INVALID_PARAMS,
941
+ );
942
+ }
943
+ webhookData.secret = value;
866
944
  }
867
945
  channels.push({ type: 'webhook', data: webhookData });
868
946
  }
@@ -879,7 +957,13 @@ USAGE:
879
957
 
880
958
  const offset = parseNonNegativeIntegerOption(options.offset, 'offset');
881
959
  const limit = parseNonNegativeIntegerOption(options.limit, 'limit');
882
- const tokenAddress = parseStringFilter(options['token-address'], 'token-address');
960
+ // --token-address is the old name of --token.
961
+ const token = parseStringFilter(options.token, 'token');
962
+ const legacyToken = parseStringFilter(options['token-address'], 'token-address');
963
+ if (token && legacyToken) {
964
+ throw new NansenError(`--token ${token} and --token-address ${legacyToken} are the same input; pass one.`, ErrorCode.INVALID_PARAMS);
965
+ }
966
+ const tokenAddress = token ?? legacyToken;
883
967
  const chainFilter = parseStringFilter(options.chain, 'chain');
884
968
 
885
969
  const results = await apiInstance.alertsList();
@@ -1019,6 +1103,9 @@ USAGE:
1019
1103
  }
1020
1104
 
1021
1105
  try {
1106
+ if (sub === 'create' || sub === 'update') {
1107
+ webhookSecret = await resolveWebhookSecret(options, flags, { env, stdin, stdinTTY });
1108
+ }
1022
1109
  const result = await handlers[sub]();
1023
1110
  return flags.reveal ? result : redactAlertSecrets(result);
1024
1111
  } catch (err) {
@@ -1046,7 +1133,8 @@ USAGE:
1046
1133
  // API error bodies (message and details) can echo the submitted channels,
1047
1134
  // and the hint above quotes the webhook URL; all are masked here unless
1048
1135
  // --reveal is passed.
1049
- throw flags.reveal ? error : redactAlertError(error, options, sentPayload);
1136
+ const redactOptions = webhookSecret ? { ...options, 'webhook-secret': webhookSecret.value } : options;
1137
+ throw flags.reveal ? error : redactAlertError(error, redactOptions, sentPayload);
1050
1138
  }
1051
1139
  },
1052
1140
  };
@@ -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);
@@ -32,7 +33,6 @@ export const UNSCHEMA_COMMANDS = {
32
33
  description: 'Show release history',
33
34
  options: { since: { type: 'string', description: 'Only show versions at or above this one' } },
34
35
  },
35
- help: { description: 'Show the top-level help' },
36
36
  };
37
37
 
38
38
  /**
@@ -41,7 +41,9 @@ export const UNSCHEMA_COMMANDS = {
41
41
  * teaches the spelling we are trying to retire.
42
42
  */
43
43
  export const EXCLUDED_COMMANDS = new Set([
44
- 'smart-money', 'profiler', 'token', 'search', 'portfolio', 'points', 'prediction-market',
44
+ 'smart-money', 'profiler', 'token', 'search', 'portfolio', 'prediction-market',
45
+ // Removed commands that still answer COMMAND_UNAVAILABLE.
46
+ ...UNAVAILABLE_COMMANDS,
45
47
  'quote', 'execute',
46
48
  // Undocumented top-level alias of `trade bridge-status`: reachable because
47
49
  // runCLI spreads buildTradingCommands over the root, absent from HELP.
@@ -49,7 +49,7 @@ function parseTimeframeDays(value) {
49
49
  if (value === undefined || value === null) return undefined;
50
50
  const trimmed = String(value).trim();
51
51
  if (!/^[1-9]\d*$/.test(trimmed)) {
52
- throw new NansenError('--timeframe-days must be a positive integer', ErrorCode.INVALID_PARAMS);
52
+ throw new NansenError('--days must be a positive integer', ErrorCode.INVALID_PARAMS);
53
53
  }
54
54
  return parseInt(trimmed, 10);
55
55
  }
@@ -114,7 +114,7 @@ const SUB_HELP = {
114
114
  'chain-rank': `nansen research chain-rank — Rank chains by growth metrics
115
115
 
116
116
  USAGE:
117
- nansen research chain-rank [--timeframe-days 7|30|365] [--chain-type all|evm]`,
117
+ nansen research chain-rank [--days 7|30|365] [--chain-type all|evm]`,
118
118
  'token-sectors': `nansen research token-sectors — List token sectors available for filtering
119
119
 
120
120
  USAGE:
@@ -126,13 +126,13 @@ USAGE:
126
126
  'smart-money-pnl-leaderboard': `nansen research smart-money-pnl-leaderboard — Rank smart money wallets by PnL
127
127
 
128
128
  USAGE:
129
- nansen research smart-money-pnl-leaderboard [--chains c1,c2] [--timeframe-days 1|7|30|90|180] [--filters '<json>'] [--sort <field[:asc|desc]>] [--page <n>] [--limit <n>]`,
129
+ nansen research smart-money-pnl-leaderboard [--chains c1,c2] [--days 1|7|30|90|180] [--filters '<json>'] [--sort <field[:asc|desc]>] [--page <n>] [--limit <n>]`,
130
130
  'position-intelligence': `nansen research position-intelligence — Aggregate Hyperliquid positions by trader cohort
131
131
 
132
132
  USAGE:
133
133
  nansen research position-intelligence --symbol <symbol>
134
134
 
135
- NOTE: --token-address is accepted as an alias for --symbol (the API request field is token_address).`,
135
+ NOTE: --coin, --token and --token-address are accepted as aliases for --symbol (the API request field is token_address).`,
136
136
  'perp-pnl-summary': `nansen research perp-pnl-summary — Summarize realized Hyperliquid PnL for an address
137
137
 
138
138
  USAGE:
@@ -146,30 +146,30 @@ NOTE: --block-timestamp is required for bitcoin, tron, ton, starknet, and sui.`,
146
146
  'historical-dex-trades': `nansen research historical-dex-trades — Historical DEX trades for a token
147
147
 
148
148
  USAGE:
149
- nansen research historical-dex-trades --token-address <addr> --from-date <YYYY-MM-DD> --to-date <YYYY-MM-DD> [--chain <chain>]`,
149
+ nansen research historical-dex-trades --token <addr> --from-date <YYYY-MM-DD> --to-date <YYYY-MM-DD> [--chain <chain>]`,
150
150
  'historical-pnl-leaderboard': `nansen research historical-pnl-leaderboard — Historical PnL leaderboard for a token
151
151
 
152
152
  USAGE:
153
- nansen research historical-pnl-leaderboard --token-address <addr> --from-date <YYYY-MM-DD> --to-date <YYYY-MM-DD> [--chain <chain>]`,
153
+ nansen research historical-pnl-leaderboard --token <addr> --from-date <YYYY-MM-DD> --to-date <YYYY-MM-DD> [--chain <chain>]`,
154
154
  'historical-token-flow-summary': `nansen research historical-token-flow-summary — Historical token flow summary
155
155
 
156
156
  USAGE:
157
- nansen research historical-token-flow-summary --token-address <addr> --from-date <YYYY-MM-DD> --to-date <YYYY-MM-DD> [--chain <chain>]
157
+ nansen research historical-token-flow-summary --token <addr> --from-date <YYYY-MM-DD> --to-date <YYYY-MM-DD> [--chain <chain>]
158
158
 
159
159
  NOTE: This endpoint does not support pagination.
160
160
  Whale, public figure, top PnL and exchange label history starts 2025-03-11, so those fields are null for an earlier --to-date.`,
161
161
  'historical-token-quant-scores': `nansen research historical-token-quant-scores — Historical token quantitative scores
162
162
 
163
163
  USAGE:
164
- nansen research historical-token-quant-scores --token-address <addr> --as-of-date <YYYY-MM-DD> [--chain <chain>]`,
164
+ nansen research historical-token-quant-scores --token <addr> --as-of-date <YYYY-MM-DD> [--chain <chain>]`,
165
165
  'historical-top-holders': `nansen research historical-top-holders — Historical top holders of a token
166
166
 
167
167
  USAGE:
168
- nansen research historical-top-holders --token-address <addr> --as-of-date <YYYY-MM-DD> [--chain <chain>]`,
168
+ nansen research historical-top-holders --token <addr> --as-of-date <YYYY-MM-DD> [--chain <chain>]`,
169
169
  'historical-who-bought-sold': `nansen research historical-who-bought-sold — Historical buyers/sellers of a token
170
170
 
171
171
  USAGE:
172
- nansen research historical-who-bought-sold --token-address <addr> --from-date <YYYY-MM-DD> --to-date <YYYY-MM-DD> [--buy-or-sell BUY|SELL] [--chain <chain>]`,
172
+ nansen research historical-who-bought-sold --token <addr> --from-date <YYYY-MM-DD> --to-date <YYYY-MM-DD> [--buy-or-sell BUY|SELL] [--chain <chain>]`,
173
173
  'historical-smart-money-balances': `nansen research historical-smart-money-balances — Historical smart money token balances
174
174
 
175
175
  USAGE:
@@ -179,7 +179,7 @@ NOTE: This endpoint does not support order_by.`,
179
179
  'historical-token-screener': `nansen research historical-token-screener — Historical token screener
180
180
 
181
181
  USAGE:
182
- nansen research historical-token-screener --timeframe-days <n> --to-date <YYYY-MM-DD> [--chains c1,c2]`,
182
+ nansen research historical-token-screener --days <n> --to-date <YYYY-MM-DD> [--chains c1,c2]`,
183
183
  'historical-wallet-balances': `nansen research historical-wallet-balances — Historical token balances for a wallet
184
184
 
185
185
  USAGE:
@@ -198,7 +198,7 @@ USAGE:
198
198
  'historical-token-ohlcv': `nansen research historical-token-ohlcv — Historical token OHLCV candles
199
199
 
200
200
  USAGE:
201
- nansen research historical-token-ohlcv --token-address <addr> --from-date <date> --timeframe <5m|15m|30m|1h|4h|1d|1w> (--as-of-date <date> | --as-of-ts <timestamp>) [--chain <chain>] [--apply-blacklist-filter <true|false>]`,
201
+ nansen research historical-token-ohlcv --token <addr|symbol> --from-date <date> --interval <5m|15m|30m|1h|4h|1d|1w> (--as-of-date <date> | --as-of-ts <timestamp>) [--chain <chain>] [--apply-blacklist-filter <true|false>]`,
202
202
  };
203
203
 
204
204
  export function buildResearchCommands(deps = {}) {
@@ -226,7 +226,7 @@ export function buildResearchCommands(deps = {}) {
226
226
 
227
227
  for (const [name, example] of [
228
228
  ['chain', 'solana'], ['chains', 'solana'], ['chain-type', 'all'],
229
- ['timeframe', '1d'], ['timeframe-days', '7'],
229
+ ['interval', '1d'], ['days', '7'],
230
230
  ]) {
231
231
  rejectBlankOption(options[name], name, example);
232
232
  }
@@ -238,10 +238,10 @@ export function buildResearchCommands(deps = {}) {
238
238
  const asOfDate = options['as-of-date'];
239
239
 
240
240
  if (sub === 'chain-rank') {
241
- const timeFrame = parseTimeframeDays(options['timeframe-days']) ?? 7;
241
+ const timeFrame = parseTimeframeDays(options.days) ?? 7;
242
242
  if (!CHAIN_RANK_TIMEFRAMES.has(timeFrame)) {
243
243
  throw new NansenError(
244
- `--timeframe-days must be one of: ${[...CHAIN_RANK_TIMEFRAMES].join(', ')}`,
244
+ `--days must be one of: ${[...CHAIN_RANK_TIMEFRAMES].join(', ')}`,
245
245
  ErrorCode.INVALID_PARAMS,
246
246
  );
247
247
  }
@@ -265,10 +265,10 @@ export function buildResearchCommands(deps = {}) {
265
265
  }
266
266
 
267
267
  if (sub === 'smart-money-pnl-leaderboard') {
268
- const timeframe = parseTimeframeDays(options['timeframe-days']) ?? 7;
268
+ const timeframe = parseTimeframeDays(options.days) ?? 7;
269
269
  if (!SM_PNL_TIMEFRAME_DAYS.includes(timeframe)) {
270
270
  throw new NansenError(
271
- `--timeframe-days must be one of: ${SM_PNL_TIMEFRAME_DAYS.join(', ')}`,
271
+ `--days must be one of: ${SM_PNL_TIMEFRAME_DAYS.join(', ')}`,
272
272
  ErrorCode.INVALID_PARAMS,
273
273
  );
274
274
  }
@@ -280,10 +280,10 @@ export function buildResearchCommands(deps = {}) {
280
280
  }
281
281
 
282
282
  if (sub === 'position-intelligence') {
283
- const symbol = String(options.symbol || options['token-address'] || options.token || '').trim();
283
+ const symbol = String(options.symbol || '').trim();
284
284
  if (!symbol) {
285
285
  throw new NansenError(
286
- 'Required: --symbol (or --token-address)',
286
+ 'Required: --symbol',
287
287
  ErrorCode.MISSING_PARAM,
288
288
  );
289
289
  }
@@ -299,11 +299,11 @@ export function buildResearchCommands(deps = {}) {
299
299
  }
300
300
 
301
301
  if (sub === 'historical-token-ohlcv') {
302
- const tokenAddress = options['token-address'] || options.token;
302
+ const tokenAddress = options.token;
303
303
  const asOfTs = options['as-of-ts'];
304
304
  requireOptions(
305
- { 'token-address': tokenAddress, 'from-date': fromDate, timeframe: options.timeframe },
306
- ['token-address', 'from-date', 'timeframe'],
305
+ { token: tokenAddress, 'from-date': fromDate, interval: options.interval },
306
+ ['token', 'from-date', 'interval'],
307
307
  );
308
308
  if (!asOfDate && !asOfTs) {
309
309
  throw new NansenError(
@@ -323,7 +323,7 @@ export function buildResearchCommands(deps = {}) {
323
323
  fromDate,
324
324
  asOfDate,
325
325
  asOfTs,
326
- timeframe: options.timeframe,
326
+ timeframe: options.interval,
327
327
  applyBlacklistFilter: parseBooleanOption(options, flags, 'apply-blacklist-filter'),
328
328
  });
329
329
  }
@@ -347,22 +347,22 @@ export function buildResearchCommands(deps = {}) {
347
347
  // Range-based token endpoints (require --from-date + --to-date)
348
348
  const rangeTokenHandlers = {
349
349
  'historical-dex-trades': () => apiInstance.researchDexTrades({
350
- tokenAddress: options['token-address'] || options.token,
350
+ tokenAddress: options.token,
351
351
  chain: options.chain,
352
352
  fromDate, toDate, filters, orderBy, pagination,
353
353
  }),
354
354
  'historical-pnl-leaderboard': () => apiInstance.researchPnlLeaderboard({
355
- tokenAddress: options['token-address'] || options.token,
355
+ tokenAddress: options.token,
356
356
  chain: options.chain,
357
357
  fromDate, toDate, filters, orderBy, pagination,
358
358
  }),
359
359
  'historical-token-flow-summary': () => apiInstance.researchTokenFlowSummary({
360
- tokenAddress: options['token-address'] || options.token,
360
+ tokenAddress: options.token,
361
361
  chain: options.chain,
362
362
  fromDate, toDate,
363
363
  }),
364
364
  'historical-who-bought-sold': () => apiInstance.researchWhoBoughtSold({
365
- tokenAddress: options['token-address'] || options.token,
365
+ tokenAddress: options.token,
366
366
  chain: options.chain,
367
367
  buyOrSell: options['buy-or-sell'],
368
368
  fromDate, toDate, filters, orderBy, pagination,
@@ -371,8 +371,8 @@ export function buildResearchCommands(deps = {}) {
371
371
 
372
372
  if (rangeTokenHandlers[sub]) {
373
373
  requireOptions(
374
- { 'token-address': options['token-address'] || options.token, 'from-date': fromDate, 'to-date': toDate },
375
- ['token-address', 'from-date', 'to-date'],
374
+ { token: options.token, 'from-date': fromDate, 'to-date': toDate },
375
+ ['token', 'from-date', 'to-date'],
376
376
  );
377
377
  if (sub === 'historical-token-flow-summary' && (options.page || options.limit)) {
378
378
  throw new NansenError(
@@ -386,12 +386,12 @@ export function buildResearchCommands(deps = {}) {
386
386
  // As-of-date token endpoints (require --as-of-date)
387
387
  const asOfTokenHandlers = {
388
388
  'historical-token-quant-scores': () => apiInstance.researchTokenQuantScores({
389
- tokenAddress: options['token-address'] || options.token,
389
+ tokenAddress: options.token,
390
390
  chain: options.chain,
391
391
  asOfDate, filters, orderBy, pagination,
392
392
  }),
393
393
  'historical-top-holders': () => apiInstance.researchTopHolders({
394
- tokenAddress: options['token-address'] || options.token,
394
+ tokenAddress: options.token,
395
395
  chain: options.chain,
396
396
  asOfDate, filters, orderBy, pagination,
397
397
  }),
@@ -399,8 +399,8 @@ export function buildResearchCommands(deps = {}) {
399
399
 
400
400
  if (asOfTokenHandlers[sub]) {
401
401
  requireOptions(
402
- { 'token-address': options['token-address'] || options.token, 'as-of-date': asOfDate },
403
- ['token-address', 'as-of-date'],
402
+ { token: options.token, 'as-of-date': asOfDate },
403
+ ['token', 'as-of-date'],
404
404
  );
405
405
  return asOfTokenHandlers[sub]();
406
406
  }
@@ -420,8 +420,8 @@ export function buildResearchCommands(deps = {}) {
420
420
  }
421
421
 
422
422
  if (sub === 'historical-token-screener') {
423
- const timeframeDays = parseTimeframeDays(options['timeframe-days']);
424
- requireOptions({ 'timeframe-days': timeframeDays, 'to-date': options['to-date'] }, ['timeframe-days', 'to-date']);
423
+ const timeframeDays = parseTimeframeDays(options.days);
424
+ requireOptions({ days: timeframeDays, 'to-date': options['to-date'] }, ['days', 'to-date']);
425
425
  return apiInstance.researchTokenScreener({
426
426
  chains: parseChains(options),
427
427
  timeframeDays,
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.' },
@@ -165,6 +166,7 @@ export const ERROR_CODES = {
165
166
  RPC_JSON_ERROR: { group: 'trade', description: 'The RPC answered with a body that is not JSON.' },
166
167
  RPC_NETWORK_ERROR: { group: 'trade', description: 'The CLI could not reach the RPC.', retry: true },
167
168
  CONFIRMATION_DECLINED: { group: 'trade', description: 'The confirmation prompt was declined; nothing was signed.' },
169
+ CONFIRMATION_REQUIRED: { group: 'trade', description: 'NANSEN_REQUIRE_CONFIRM is set and stdin is not a terminal; nothing was signed. Pass --yes to proceed or --dry-run to preview.' },
168
170
  CONFIRMATION_UNAVAILABLE: { group: 'trade', description: 'Confirmation is required but no terminal is available. Pass --yes to confirm.' },
169
171
 
170
172
  // ── Bridge ──
@@ -183,6 +185,7 @@ export const ERROR_CODES = {
183
185
  BUILDER_FEE_TOO_HIGH: { group: 'perp', description: 'The builder fee is above the allowed ceiling.' },
184
186
  BUILDER_FEE_UNAVAILABLE: { group: 'perp', description: 'The builder fee could not be read or approved.' },
185
187
  META_UNAVAILABLE: { group: 'perp', description: 'Hyperliquid asset metadata is not available.', retry: true },
188
+ 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
189
  SANCTIONED: { group: 'perp', description: 'The address failed sanctions screening.' },
187
190
  SCREENING_UNAVAILABLE: { group: 'perp', description: 'Sanctions screening is not available, so the action was refused.', retry: true },
188
191
  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,
@@ -13,6 +15,11 @@
13
15
  * the command proceeds without asking, so no automated workflow can hang on a
14
16
  * question nobody is there to answer. `--yes` is still accepted there and is
15
17
  * simply a no-op. Declining the prompt exits 1 with nothing signed.
18
+ *
19
+ * Opt-in stop point: an operator who wants their agent to pause before moving
20
+ * funds sets `NANSEN_REQUIRE_CONFIRM=1`. With it set and stdin not a terminal,
21
+ * a run without --yes / NANSEN_YES fails with CONFIRMATION_REQUIRED before the
22
+ * command does anything else; --dry-run still previews. Unset, nothing changes.
16
23
  */
17
24
 
18
25
  import { CommandError } from './api.js';
@@ -21,21 +28,49 @@ import { CommandError } from './api.js';
21
28
  // empty string) leaves the confirmation in place.
22
29
  const TRUTHY_ENV_VALUES = new Set(['1', 'true', 'yes', 'on']);
23
30
 
24
- export function isYesEnvSet(env = process.env) {
25
- const raw = env?.NANSEN_YES;
31
+ function isTruthyEnv(raw) {
26
32
  return typeof raw === 'string' && TRUTHY_ENV_VALUES.has(raw.trim().toLowerCase());
27
33
  }
28
34
 
35
+ export function isYesEnvSet(env = process.env) {
36
+ return isTruthyEnv(env?.NANSEN_YES);
37
+ }
38
+
39
+ // Same spellings as NANSEN_YES. Anything else keeps today's behaviour.
40
+ export function isRequireConfirmEnvSet(env = process.env) {
41
+ return isTruthyEnv(env?.NANSEN_REQUIRE_CONFIRM);
42
+ }
43
+
44
+ function confirmationRequiredError() {
45
+ return new CommandError(
46
+ 'Confirmation required: NANSEN_REQUIRE_CONFIRM is set and stdin is not a terminal, so nothing was signed or broadcast. '
47
+ + 'Pass --yes (or set NANSEN_YES=1) to proceed, or --dry-run to preview.',
48
+ 'CONFIRMATION_REQUIRED',
49
+ );
50
+ }
51
+
29
52
  /**
30
53
  * Read the guard's inputs off the parsed flags. `-y` arrives as `flags.y`
31
54
  * because single-dash tokens are always parsed as valueless flags.
55
+ *
56
+ * Every guarded command calls this first, so the NANSEN_REQUIRE_CONFIRM refusal
57
+ * is thrown here, before any API request. Those requests can sign an x402
58
+ * payment on a 402 response, so refusing only at guardExecution could spend
59
+ * funds and then claim nothing was signed.
32
60
  */
33
61
  export function resolveExecuteGuard(flags = {}, { env = process.env, isTTY = false } = {}) {
34
- return {
62
+ const guard = {
35
63
  dryRun: Boolean(flags['dry-run']),
36
64
  assumeYes: Boolean(flags.yes || flags.y) || isYesEnvSet(env),
37
65
  isTTY: Boolean(isTTY),
66
+ requireConfirm: isRequireConfirmEnvSet(env),
38
67
  };
68
+ if (needsConfirmationOffTerminal(guard)) throw confirmationRequiredError();
69
+ return guard;
70
+ }
71
+
72
+ function needsConfirmationOffTerminal({ dryRun, assumeYes, isTTY, requireConfirm }) {
73
+ return Boolean(requireConfirm) && !dryRun && !assumeYes && !isTTY;
39
74
  }
40
75
 
41
76
  /**
@@ -68,18 +103,28 @@ export async function guardExecution({
68
103
  dryRun = false,
69
104
  assumeYes = false,
70
105
  isTTY = false,
106
+ requireConfirm = false,
71
107
  promptFn,
72
108
  log = () => {},
73
109
  confirmationLog = log,
74
110
  question = 'Broadcast this transaction? [y/N] ',
111
+ dryRunNotice = [
112
+ '\n DRY RUN — nothing was broadcast. No transaction was signed and the quote was not consumed.',
113
+ ' Re-run without --dry-run to sign and broadcast it.\n',
114
+ ],
75
115
  }) {
76
116
  if (dryRun) {
77
117
  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');
118
+ for (const line of dryRunNotice) log(line);
80
119
  return false;
81
120
  }
82
121
 
122
+ // Backstop for callers that build the guard themselves; resolveExecuteGuard
123
+ // normally refuses this case before the command makes any request.
124
+ if (needsConfirmationOffTerminal({ dryRun, assumeYes, isTTY, requireConfirm })) {
125
+ throw confirmationRequiredError();
126
+ }
127
+
83
128
  // Non-interactive stdin (agents, CI, pipes): unchanged, deterministic, never
84
129
  // blocked on a prompt. --yes is accepted here and does nothing.
85
130
  if (!isTTY || assumeYes) return true;