nansen-cli 2.5.0 → 2.6.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.
@@ -544,34 +544,6 @@ export function buildCommonTokenTransferData(options) {
544
544
  return data;
545
545
  }
546
546
 
547
- /**
548
- * Build the data payload for smart-contract-call alerts from named flags.
549
- */
550
- export function buildSmartContractCallData(options) {
551
- const data = {};
552
-
553
- const chains = parseChains(options.chains);
554
- if (chains) data.chains = chains;
555
-
556
- const usdRange = buildRange(options['usd-min'], options['usd-max'], 'usd');
557
- if (usdRange) data.usdValue = usdRange;
558
-
559
- const signatureHash = parseCsvOption(options['signature-hash'], 'signature-hash');
560
- if (signatureHash) data.signatureHash = signatureHash;
561
-
562
- const callers = parseSubjects(options.caller, 'caller');
563
- const contracts = parseSubjects(options.contract, 'contract');
564
- const excludeCallers = parseSubjects(options['exclude-caller'], 'exclude-caller');
565
- const excludeContracts = parseSubjects(options['exclude-contract'], 'exclude-contract');
566
-
567
- if (callers) data.inclusion = { ...data.inclusion, caller: callers };
568
- if (contracts) data.inclusion = { ...data.inclusion, smartContract: contracts };
569
- if (excludeCallers) data.exclusion = { ...data.exclusion, caller: excludeCallers };
570
- if (excludeContracts) data.exclusion = { ...data.exclusion, smartContract: excludeContracts };
571
-
572
- return data;
573
- }
574
-
575
547
  /**
576
548
  * Type-specific defaults for required fields.
577
549
  * Applied in buildAlertData so payloads always satisfy the backend schema.
@@ -602,16 +574,43 @@ const TYPE_DEFAULTS = {
602
574
  inclusion: {},
603
575
  exclusion: {},
604
576
  },
605
- 'smart-contract-call': {
606
- chains: [],
607
- events: ['smart-contract-call'],
608
- usdValue: {},
609
- signatureHash: [],
610
- inclusion: { caller: [], smartContract: [] },
611
- exclusion: { caller: [], smartContract: [] },
612
- },
613
577
  };
614
578
 
579
+ /** Alert types the backend accepts. */
580
+ export const ALERT_TYPES = ['sm-token-flows', 'common-token-transfer'];
581
+
582
+ /** Flags that only the retired smart-contract-call type used. */
583
+ const RETIRED_CONTRACT_CALL_FLAGS = ['signature-hash', 'caller', 'contract', 'exclude-caller', 'exclude-contract'];
584
+
585
+ function retiredTypeError() {
586
+ return new NansenError(
587
+ `The smart-contract-call alert type was retired and can no longer be created or updated. Use one of: ${ALERT_TYPES.join(', ')}.`,
588
+ ErrorCode.INVALID_PARAMS,
589
+ );
590
+ }
591
+
592
+ /**
593
+ * Reject create/update input the backend can no longer act on, before any
594
+ * stdin read or request. The smart-contract-call type was retired, and its
595
+ * flags would otherwise be ignored without a word, since alerts does not
596
+ * reject unknown flags. A bare flag lands in `flags`, a valued one in `options`.
597
+ */
598
+ export function checkAlertInput(options = {}, flags = {}) {
599
+ const valid = ALERT_TYPES.join(', ');
600
+ const type = options.type;
601
+ if (type === 'smart-contract-call') throw retiredTypeError();
602
+ if (type !== undefined && !ALERT_TYPES.includes(type)) {
603
+ throw new NansenError(`Invalid --type "${type}". Use one of: ${valid}.`, ErrorCode.INVALID_PARAMS);
604
+ }
605
+ const retired = RETIRED_CONTRACT_CALL_FLAGS.find(f => options[f] !== undefined || flags[f] !== undefined);
606
+ if (retired) {
607
+ throw new NansenError(
608
+ `--${retired} was only used by smart-contract-call alerts, which were retired. Remove it; supported types: ${valid}.`,
609
+ ErrorCode.INVALID_PARAMS,
610
+ );
611
+ }
612
+ }
613
+
615
614
  /**
616
615
  * Build the alert data payload from named flags, dispatching on type.
617
616
  * --data '<json>' is merged on top as an escape-hatch override.
@@ -626,8 +625,6 @@ export function buildAlertData(options, { applyDefaults = true } = {}) {
626
625
  data = buildSmTokenFlowsData(options);
627
626
  } else if (options.type === 'common-token-transfer') {
628
627
  data = buildCommonTokenTransferData(options);
629
- } else if (options.type === 'smart-contract-call') {
630
- data = buildSmartContractCallData(options);
631
628
  } else {
632
629
  // No type — only --chains and --data are valid; warn if type-specific flags are present
633
630
  const typeSpecificFlags = [
@@ -636,8 +633,7 @@ export function buildAlertData(options, { applyDefaults = true } = {}) {
636
633
  'netflow-1h-min', 'netflow-1h-max', 'netflow-1d-min', 'netflow-1d-max', 'netflow-7d-min', 'netflow-7d-max',
637
634
  'events', 'usd-min', 'usd-max', 'token-amount-min', 'token-amount-max',
638
635
  'token', 'exclude-token',
639
- 'subject', 'counterparty', 'signature-hash', 'caller', 'contract',
640
- 'exclude-caller', 'exclude-contract', 'exclude-from', 'exclude-to',
636
+ 'subject', 'counterparty', 'exclude-from', 'exclude-to',
641
637
  'token-sector', 'exclude-token-sector', 'token-age-min', 'token-age-max',
642
638
  'market-cap-min', 'market-cap-max', 'fdv-min', 'fdv-max',
643
639
  ];
@@ -655,7 +651,7 @@ export function buildAlertData(options, { applyDefaults = true } = {}) {
655
651
 
656
652
  // Apply type defaults underneath so all required fields are present.
657
653
  // Use structuredClone to avoid shared mutable references, and deep-merge
658
- // inclusion/exclusion so partial flags (e.g. --caller without --contract)
654
+ // inclusion/exclusion so partial flags (e.g. --token without --token-sector)
659
655
  // don't drop sibling required sub-fields.
660
656
  if (applyDefaults && TYPE_DEFAULTS[options.type]) {
661
657
  const defaults = structuredClone(TYPE_DEFAULTS[options.type]);
@@ -733,25 +729,12 @@ export function validateAlertData(type, data) {
733
729
  );
734
730
  }
735
731
  }
736
-
737
- if (type === 'smart-contract-call') {
738
- const hasCallers = Array.isArray(data.inclusion?.caller) && data.inclusion.caller.length > 0;
739
- const hasContracts = Array.isArray(data.inclusion?.smartContract) && data.inclusion.smartContract.length > 0;
740
- const hasSignatureHash = Array.isArray(data.signatureHash) && data.signatureHash.length > 0;
741
- if (!hasCallers && !hasContracts && !hasSignatureHash) {
742
- throw new NansenError(
743
- 'smart-contract-call requires at least one --caller, --contract, or --signature-hash',
744
- ErrorCode.INVALID_PARAMS,
745
- );
746
- }
747
- }
748
732
  }
749
733
 
750
734
  // ============= Command Builder =============
751
735
 
752
736
  const TIME_WINDOW_BY_TYPE = {
753
737
  'common-token-transfer': 'realtime',
754
- 'smart-contract-call': 'realtime',
755
738
  'sm-token-flows': '1h',
756
739
  };
757
740
 
@@ -781,15 +764,15 @@ Run: nansen alerts <subcommand> --help`,
781
764
  list: `nansen alerts list — List all alerts
782
765
 
783
766
  USAGE:
784
- nansen alerts list [--table] [--pretty] [--type <type>] [--enabled|--disabled] [--token-address <addr>] [--chain <chain>] [--limit <n>] [--offset <n>] [--reveal]
767
+ nansen alerts list [--table] [--pretty] [--type <type>] [--enabled|--disabled] [--token <addr>] [--chain <chain>] [--limit <n>] [--offset <n>] [--reveal]
785
768
 
786
769
  OPTIONS:
787
770
  --table Human-readable table output (columns: ID, NAME, TYPE, ENABLED, CHANNELS)
788
771
  --pretty Indented JSON output
789
772
  --reveal Show full channel webhook URLs and secrets (redacted by default)
790
- --type <type> Filter by alert type (sm-token-flows, common-token-transfer, smart-contract-call)
773
+ --type <type> Filter by alert type (sm-token-flows, common-token-transfer)
791
774
  --enabled / --disabled Filter by enabled state
792
- --token-address <addr> Filter by token address
775
+ --token <addr> Filter by token address (alias --token-address)
793
776
  --chain <chain> Filter by chain
794
777
  --limit <n> Max results
795
778
  --offset <n> Skip first N results
@@ -806,7 +789,7 @@ USAGE:
806
789
 
807
790
  REQUIRED:
808
791
  --name <name> Alert name
809
- --type <type> sm-token-flows | common-token-transfer | smart-contract-call
792
+ --type <type> sm-token-flows | common-token-transfer
810
793
  At least one channel: --telegram <chatId> | --slack <url> | --discord <url> | --webhook <url>
811
794
 
812
795
  OPTIONS (all types):
@@ -838,11 +821,6 @@ OPTIONS (common-token-transfer):
838
821
  --token-age-min/max <days> --market-cap-min/max <usd>
839
822
  --exclude-from <type:value> --exclude-to <type:value> (repeatable)
840
823
 
841
- OPTIONS (smart-contract-call):
842
- --usd-min/max <usd> --signature-hash <hash> (repeatable)
843
- --caller <type:value> --exclude-caller <type:value> (repeatable)
844
- --contract <type:value> --exclude-contract <type:value> (repeatable)
845
-
846
824
  SUBJECT TYPES: address, entity, label, custom-label
847
825
  CHAIN ALIASES: Hyperliquid = hyperevm, BSC = bnb
848
826
 
@@ -851,7 +829,6 @@ NOTE: Use single quotes for names with $ or special chars: --name 'SM >$1M'
851
829
  EXAMPLES:
852
830
  nansen alerts create --name 'ETH SM Inflow' --type sm-token-flows --chains ethereum --telegram 5238612255 --inflow-1h-min 1000000
853
831
  nansen alerts create --name 'USDC Transfers' --type common-token-transfer --chains ethereum --telegram 5238612255 --events send,receive --usd-min 1000000 --subject label:"Centralized Exchange"
854
- nansen alerts create --name 'Contract Calls' --type smart-contract-call --chains ethereum --telegram 5238612255 --signature-hash 0xa9059cbb --caller address:0xabc
855
832
  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
833
 
857
834
  WEBHOOK SIGNING SECRET (minimum 16 characters, webhook only):
@@ -890,7 +867,10 @@ OPTIONS:
890
867
  delete: `nansen alerts delete — Delete an alert
891
868
 
892
869
  USAGE:
893
- nansen alerts delete <id>`,
870
+ nansen alerts delete <id>
871
+
872
+ OPTIONS:
873
+ --reveal Show full channel URLs and secrets in the response (redacted by default)`,
894
874
  };
895
875
 
896
876
  if (!sub || sub === 'help') {
@@ -954,7 +934,13 @@ USAGE:
954
934
 
955
935
  const offset = parseNonNegativeIntegerOption(options.offset, 'offset');
956
936
  const limit = parseNonNegativeIntegerOption(options.limit, 'limit');
957
- const tokenAddress = parseStringFilter(options['token-address'], 'token-address');
937
+ // --token-address is the old name of --token.
938
+ const token = parseStringFilter(options.token, 'token');
939
+ const legacyToken = parseStringFilter(options['token-address'], 'token-address');
940
+ if (token && legacyToken) {
941
+ throw new NansenError(`--token ${token} and --token-address ${legacyToken} are the same input; pass one.`, ErrorCode.INVALID_PARAMS);
942
+ }
943
+ const tokenAddress = token ?? legacyToken;
958
944
  const chainFilter = parseStringFilter(options.chain, 'chain');
959
945
 
960
946
  const results = await apiInstance.alertsList();
@@ -1035,6 +1021,7 @@ USAGE:
1035
1021
  const existing = await apiInstance.alertsGet(id);
1036
1022
  if (!existing) throw new NansenError(`Alert not found: ${id}`, ErrorCode.NOT_FOUND);
1037
1023
  const existingType = existing.type ?? existing.data?.type;
1024
+ if (existingType === 'smart-contract-call') throw retiredTypeError();
1038
1025
  if (options.type && options.type !== existingType) {
1039
1026
  throw new NansenError(
1040
1027
  `Cannot change alert type (${existingType} → ${options.type}). Delete and recreate the alert instead.`,
@@ -1095,6 +1082,7 @@ USAGE:
1095
1082
 
1096
1083
  try {
1097
1084
  if (sub === 'create' || sub === 'update') {
1085
+ checkAlertInput(options, flags);
1098
1086
  webhookSecret = await resolveWebhookSecret(options, flags, { env, stdin, stdinTTY });
1099
1087
  }
1100
1088
  const result = await handlers[sub]();
@@ -33,7 +33,6 @@ export const UNSCHEMA_COMMANDS = {
33
33
  description: 'Show release history',
34
34
  options: { since: { type: 'string', description: 'Only show versions at or above this one' } },
35
35
  },
36
- help: { description: 'Show the top-level help' },
37
36
  };
38
37
 
39
38
  /**
@@ -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/crypto.js CHANGED
@@ -15,6 +15,23 @@ export function keccak256(input) {
15
15
  return Buffer.from(hash);
16
16
  }
17
17
 
18
+ // ============= EIP-55 =============
19
+
20
+ /**
21
+ * EIP-55 mixed-case checksum form of a 20-byte hex address (with or without
22
+ * 0x, any case). Each hex letter is uppercased when the matching nibble of
23
+ * keccak256(lowercase hex) is 8 or more.
24
+ */
25
+ export function toChecksumAddress(address) {
26
+ const hex = String(address).replace(/^0x/i, '').toLowerCase();
27
+ const hash = keccak256(Buffer.from(hex, 'utf8')).toString('hex');
28
+ let out = '0x';
29
+ for (let i = 0; i < hex.length; i++) {
30
+ out += parseInt(hash[i], 16) >= 8 ? hex[i].toUpperCase() : hex[i];
31
+ }
32
+ return out;
33
+ }
34
+
18
35
  // ============= secp256k1 ECDSA =============
19
36
 
20
37
  /**
@@ -166,6 +166,7 @@ export const ERROR_CODES = {
166
166
  RPC_JSON_ERROR: { group: 'trade', description: 'The RPC answered with a body that is not JSON.' },
167
167
  RPC_NETWORK_ERROR: { group: 'trade', description: 'The CLI could not reach the RPC.', retry: true },
168
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.' },
169
170
  CONFIRMATION_UNAVAILABLE: { group: 'trade', description: 'Confirmation is required but no terminal is available. Pass --yes to confirm.' },
170
171
 
171
172
  // ── Bridge ──
@@ -15,6 +15,11 @@
15
15
  * the command proceeds without asking, so no automated workflow can hang on a
16
16
  * question nobody is there to answer. `--yes` is still accepted there and is
17
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.
18
23
  */
19
24
 
20
25
  import { CommandError } from './api.js';
@@ -23,21 +28,49 @@ import { CommandError } from './api.js';
23
28
  // empty string) leaves the confirmation in place.
24
29
  const TRUTHY_ENV_VALUES = new Set(['1', 'true', 'yes', 'on']);
25
30
 
26
- export function isYesEnvSet(env = process.env) {
27
- const raw = env?.NANSEN_YES;
31
+ function isTruthyEnv(raw) {
28
32
  return typeof raw === 'string' && TRUTHY_ENV_VALUES.has(raw.trim().toLowerCase());
29
33
  }
30
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
+
31
52
  /**
32
53
  * Read the guard's inputs off the parsed flags. `-y` arrives as `flags.y`
33
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.
34
60
  */
35
61
  export function resolveExecuteGuard(flags = {}, { env = process.env, isTTY = false } = {}) {
36
- return {
62
+ const guard = {
37
63
  dryRun: Boolean(flags['dry-run']),
38
64
  assumeYes: Boolean(flags.yes || flags.y) || isYesEnvSet(env),
39
65
  isTTY: Boolean(isTTY),
66
+ requireConfirm: isRequireConfirmEnvSet(env),
40
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;
41
74
  }
42
75
 
43
76
  /**
@@ -70,6 +103,7 @@ export async function guardExecution({
70
103
  dryRun = false,
71
104
  assumeYes = false,
72
105
  isTTY = false,
106
+ requireConfirm = false,
73
107
  promptFn,
74
108
  log = () => {},
75
109
  confirmationLog = log,
@@ -85,6 +119,12 @@ export async function guardExecution({
85
119
  return false;
86
120
  }
87
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
+
88
128
  // Non-interactive stdin (agents, CI, pipes): unchanged, deterministic, never
89
129
  // blocked on a prompt. --yes is accepted here and does nothing.
90
130
  if (!isTTY || assumeYes) return true;
@@ -381,8 +381,8 @@ function valueErrors(name, spec, value) {
381
381
 
382
382
  /**
383
383
  * Check a research command's options before it runs. Throws one NansenError
384
- * listing every problem (see validationError). On success it rewrites
385
- * --chain/--chains in `options` to their canonical spelling (lowercase, REST
384
+ * listing every problem (see validationError). On success it renames aliases
385
+ * to their schema name, and rewrites --chain/--chains in `options` to their canonical spelling (lowercase, REST
386
386
  * aliases such as bsc -> bnb applied), as the API itself would, and turns
387
387
  * --chains into an array.
388
388
  */
@@ -399,9 +399,18 @@ export function validateResearchInput(resolved, { flags = {}, options = {}, endp
399
399
  ...Object.entries(options).map(([name, value]) => [name, value]),
400
400
  ...Object.entries(flags).filter(([name, value]) => value && !(name in options)).map(([name, value]) => [name, value]),
401
401
  ];
402
+ const spelled = new Map(); // schema name -> the spelling that was given
402
403
  for (const [raw, value] of supplied) {
403
404
  const canonical = names.get(raw);
404
405
  if (canonical) {
406
+ // `--token A --token-address B` names one input twice; the handler
407
+ // would silently use one of them.
408
+ if (spelled.has(canonical)) {
409
+ errors.push(fieldError(`--${canonical}`, 'invalid_field_value',
410
+ `Options '--${spelled.get(canonical)}' and '--${raw}' are the same input (--${canonical}); pass one.`));
411
+ continue;
412
+ }
413
+ spelled.set(canonical, raw);
405
414
  given.set(canonical, value);
406
415
  continue;
407
416
  }
@@ -415,8 +424,12 @@ export function validateResearchInput(resolved, { flags = {}, options = {}, endp
415
424
  continue;
416
425
  }
417
426
  const field = raw.length === 1 ? `-${raw}` : `--${raw}`;
427
+ // --days is the lookback flag elsewhere; here the window is text (24h, 7d).
428
+ const hint = raw === 'days' && leaf.options?.timeframe && !names.has('days')
429
+ ? ' Use --timeframe instead (for example --timeframe 7d); this command takes a time window, not a number of days.'
430
+ : '';
418
431
  errors.push(fieldError(field, 'unknown_field',
419
- `Option '${field}' is not recognized by ${path}. Command-specific options: ${visible.join(', ') || 'none'}. Common options also apply; see: nansen schema.`));
432
+ `Option '${field}' is not recognized by ${path}.${hint} Command-specific options: ${visible.join(', ') || 'none'}. Common options also apply; see: nansen schema.`));
420
433
  }
421
434
 
422
435
  for (const [name, value] of given) {
@@ -447,9 +460,25 @@ export function validateResearchInput(resolved, { flags = {}, options = {}, endp
447
460
  }
448
461
 
449
462
  if (errors.length) throw validationError(errors);
463
+ canonicalizeOptionNames(options, flags, names);
450
464
  normalizeChainOptions(options, names);
451
465
  }
452
466
 
467
+ /**
468
+ * Move every alias to its schema name (--token-address -> --token), so a
469
+ * handler reads one name per input and an alias needs only a schema entry.
470
+ */
471
+ function canonicalizeOptionNames(options, flags, names) {
472
+ for (const [raw, canonical] of names) {
473
+ if (raw === canonical) continue;
474
+ for (const bag of [options, flags]) {
475
+ if (!Object.hasOwn(bag, raw)) continue;
476
+ bag[canonical] = bag[raw];
477
+ delete bag[raw];
478
+ }
479
+ }
480
+ }
481
+
453
482
  /** Reject an output format the CLI cannot write. */
454
483
  export function validateOutputOptions({ flags = {}, options = {} } = {}) {
455
484
  // --fields is applied after the response arrives; check its shape here so