nansen-cli 1.45.0 → 1.46.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
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  import { NansenAPI, NansenError, CommandError, ErrorCode, saveConfig, deleteConfig, getConfigFile, clearCache, getCacheDir, validateAddress, normalizeAddress, sleep } from './api.js';
7
- import { buildWalletCommands } from './wallet.js';
7
+ import { buildWalletCommands, WALLET_SUBCOMMANDS } from './wallet.js';
8
8
  import { buildBridgeCommands, formatBridgeRoutes } from './bridge.js';
9
9
  import { buildPerpCommands } from './perp.js';
10
10
  import { buildTradingCommands } from './trading.js';
@@ -14,7 +14,7 @@ import { buildAgentCommands } from './commands/agent.js';
14
14
  import { buildMcpCommands } from './commands/mcp.js';
15
15
  import { buildCompletionCommands } from './commands/completion.js';
16
16
  import { buildResearchCommands, RESEARCH_HISTORICAL_SUBCOMMANDS, RESEARCH_SUBCOMMANDS } from './commands/research.js';
17
- import { buildPagination, parseSort, parseCsvOption, rejectBlankOption } from './query-options.js';
17
+ import { buildPagination, parseSort, parseCsvOption, rejectBlankOption, parseObjectOption } from './query-options.js';
18
18
  export { buildPagination, parseSort };
19
19
  import { resolveAddress, isEnsName } from './ens.js';
20
20
  import { compareSemver } from './semver.js';
@@ -49,36 +49,53 @@ export const SCHEMA = { version: VERSION, ...schemaDefinition };
49
49
  * Returns true/false/undefined (undefined = not supplied).
50
50
  */
51
51
  export function resolveBooleanOption(options, flags, key) {
52
- if (options[key] !== undefined) {
53
- const val = String(options[key]).toLowerCase();
52
+ const optionValue = options[key];
53
+ const flagValue = flags[key];
54
+
55
+ if (Array.isArray(optionValue) || Array.isArray(flagValue) ||
56
+ (optionValue !== undefined && flagValue !== undefined)) {
57
+ throw new NansenError(`--${key} cannot be repeated`, ErrorCode.INVALID_PARAMS);
58
+ }
59
+ if (optionValue !== undefined) {
60
+ const val = String(optionValue).toLowerCase();
54
61
  if (val === 'true' || val === '1') return true;
55
62
  if (val === 'false' || val === '0') return false;
63
+ throw new NansenError(`--${key} must be true or false`, ErrorCode.INVALID_PARAMS);
56
64
  }
57
- if (flags[key] !== undefined) return Boolean(flags[key]);
65
+ if (flagValue !== undefined) return Boolean(flagValue);
58
66
  return undefined;
59
67
  }
60
68
 
61
69
  // ============= Field Filtering =============
62
70
 
63
71
  /**
64
- * Filter object to include only specified fields
65
- * Supports nested paths with dot notation (e.g., "data.results")
72
+ * Filter object to include only specified fields.
73
+ *
74
+ * A bare name ("address") matches that key at any depth. A dotted path
75
+ * ("data.results", "results.address") matches only at that position, counted
76
+ * from the root of the payload; array elements do not add a segment, so
77
+ * "results.address" selects `address` inside each item of `results`.
66
78
  */
67
79
  export function filterFields(data, fields) {
68
80
  if (!fields || fields.length === 0) return data;
69
81
 
70
- const fieldSet = new Set(fields);
82
+ const names = new Set();
83
+ const paths = new Set();
84
+ for (const field of fields) {
85
+ (field.includes('.') ? paths : names).add(field);
86
+ }
71
87
 
72
- function filterObject(obj) {
88
+ function filterObject(obj, path) {
73
89
  if (obj === null || obj === undefined) return obj;
74
90
  if (Array.isArray(obj)) {
75
- return obj.map(item => filterObject(item));
91
+ return obj.map(item => filterObject(item, path));
76
92
  }
77
93
  if (typeof obj !== 'object') return obj;
78
94
 
79
95
  const filtered = {};
80
96
  for (const key of Object.keys(obj)) {
81
- if (fieldSet.has(key)) {
97
+ const keyPath = path ? `${path}.${key}` : key;
98
+ if (names.has(key) || paths.has(keyPath)) {
82
99
  // Explicitly requested — include as-is
83
100
  filtered[key] = obj[key];
84
101
  } else if (typeof obj[key] === 'object' && obj[key] !== null) {
@@ -89,7 +106,7 @@ export function filterFields(data, fields) {
89
106
  const hasObjectElements = obj[key].length > 0 &&
90
107
  typeof obj[key][0] === 'object' && obj[key][0] !== null;
91
108
  if (hasObjectElements) {
92
- const nested = obj[key].map(item => filterObject(item))
109
+ const nested = obj[key].map(item => filterObject(item, keyPath))
93
110
  .filter(item => Object.keys(item).length > 0);
94
111
  if (nested.length > 0) {
95
112
  filtered[key] = nested;
@@ -97,7 +114,7 @@ export function filterFields(data, fields) {
97
114
  }
98
115
  } else {
99
116
  // Plain object — always recurse in case it wraps requested fields
100
- const nested = filterObject(obj[key]);
117
+ const nested = filterObject(obj[key], keyPath);
101
118
  if (nested !== null && nested !== undefined && Object.keys(nested).length > 0) {
102
119
  filtered[key] = nested;
103
120
  }
@@ -107,7 +124,7 @@ export function filterFields(data, fields) {
107
124
  return filtered;
108
125
  }
109
126
 
110
- return filterObject(data);
127
+ return filterObject(data, '');
111
128
  }
112
129
 
113
130
  /**
@@ -175,35 +192,69 @@ export const VALUELESS_FLAGS = new Set([
175
192
  'enrich', 'full', 'human', 'enabled', 'disabled', 'expert', 'json', 'offline',
176
193
  'no-simulate', 'no-verify-outcome', 'no-revoke-excessive-allowance', 'dry-run',
177
194
  'send-api-key', 'all', 'max', 'gasless', 'auto-slippage', 'unsafe-no-password',
195
+ 'reveal', 'yes',
178
196
  ]);
179
197
 
180
198
  export function parseArgs(args) {
181
199
  const result = { _: [], flags: {}, options: {} };
200
+
201
+ const addFlag = (key) => {
202
+ if (key in result.flags) {
203
+ if (!Array.isArray(result.flags[key])) result.flags[key] = [result.flags[key]];
204
+ result.flags[key].push(true);
205
+ } else {
206
+ result.flags[key] = true;
207
+ }
208
+ };
182
209
 
183
210
  for (let i = 0; i < args.length; i++) {
184
211
  const arg = args[i];
185
212
 
186
213
  if (arg.startsWith('--')) {
187
- const key = arg.slice(2);
188
- const next = args[i + 1];
214
+ const equalsIndex = arg.indexOf('=');
215
+ const inlineKey = equalsIndex === -1 ? null : arg.slice(2, equalsIndex);
216
+ // `--help=false` is neither help nor a meaningful false value: valueless
217
+ // switches only accept their bare spelling. Reject it instead of leaking
218
+ // a stale `flags['help=false']` key that no handler will ever inspect.
219
+ if (inlineKey !== null && VALUELESS_FLAGS.has(inlineKey)) {
220
+ throw new NansenError(`--${inlineKey} does not accept a value`, ErrorCode.INVALID_PARAMS);
221
+ }
222
+ // Value-taking options, including boolean options handled by
223
+ // resolveBooleanOption(), accept the conventional `--key=value` spelling.
224
+ const hasInlineValue = inlineKey !== null;
225
+ const key = hasInlineValue ? inlineKey : arg.slice(2);
226
+ const next = hasInlineValue ? arg.slice(equalsIndex + 1) : args[i + 1];
189
227
 
190
228
  if (VALUELESS_FLAGS.has(key)) {
229
+ // Repeating a switch is idempotent. Keeping the value strictly true
230
+ // avoids leaking `[true, true]` into consumers that use `=== true`.
191
231
  result.flags[key] = true;
192
232
  // `next !== undefined` rather than a truthiness check: an explicit empty
193
233
  // string is a real value, and skipping it here left `""` dangling to be
194
234
  // picked up as a positional arg on the next iteration.
195
- } else if (next !== undefined && (!next.startsWith('-') || /^-\d/.test(next))) {
196
- // Try to parse as JSON first (for objects/arrays/booleans),
197
- // but keep numeric strings as strings to avoid precision loss
198
- // and scientific notation for large integers (e.g. 1e+21).
199
- let parsedValue;
235
+ // An inline value was explicitly supplied and is always consumed, even
236
+ // when it begins with a dash; downstream option validation owns whether
237
+ // that value is meaningful. The dash guard applies only to two-token
238
+ // input, where `--key --next` denotes two separate arguments.
239
+ } else if (hasInlineValue || (next !== undefined && (!next.startsWith('-') || /^-\d/.test(next)))) {
240
+ // Try to parse as JSON so object/array options (`--filters '{}'`,
241
+ // `--order-by '[...]'`) arrive structured. Numbers stay strings to
242
+ // avoid precision loss and scientific notation for large integers
243
+ // (e.g. 1e+21). The bare keywords true/false/null stay strings too:
244
+ // no option takes a boolean or null *value*, so coercing them would
245
+ // silently retype a string option (`--sort true` used to become the
246
+ // boolean true). Boolean options read the strings 'true'/'false'
247
+ // through resolveBooleanOption().
248
+ let parsedValue = next;
200
249
  try {
201
250
  const parsed = JSON.parse(next);
202
- parsedValue = typeof parsed === 'number' ? next : parsed;
251
+ if (typeof parsed !== 'number' && typeof parsed !== 'boolean' && parsed !== null) {
252
+ parsedValue = parsed;
253
+ }
203
254
  } catch {
204
- parsedValue = next;
255
+ // Not JSON: keep the raw string.
205
256
  }
206
- i++;
257
+ if (!hasInlineValue) i++;
207
258
  // Accumulate repeated options into arrays (supports repeatable flags like --token, --subject)
208
259
  if (key in result.options) {
209
260
  if (!Array.isArray(result.options[key])) {
@@ -214,10 +265,10 @@ export function parseArgs(args) {
214
265
  result.options[key] = parsedValue;
215
266
  }
216
267
  } else {
217
- result.flags[key] = true;
268
+ addFlag(key);
218
269
  }
219
270
  } else if (arg.startsWith('-')) {
220
- result.flags[arg.slice(1)] = true;
271
+ addFlag(arg.slice(1));
221
272
  } else {
222
273
  result._.push(arg);
223
274
  }
@@ -469,21 +520,30 @@ export function formatCsv(data) {
469
520
  return lines.join('\n');
470
521
  }
471
522
 
523
+ // Render the error envelope for the non-JSON formats. CSV gets a real header
524
+ // row plus one record so the envelope stays machine-parseable; table keeps the
525
+ // leading `Error:` line and follows it with one `key: value` line per field, so
526
+ // code, status and details are not dropped on the way to the terminal.
527
+ function formatErrorText(data, { csv = false } = {}) {
528
+ if (csv) return formatCsv(data);
529
+ const lines = [`Error: ${data.error}`];
530
+ for (const [key, val] of Object.entries(data)) {
531
+ if (key === 'success' || key === 'error' || val == null) continue;
532
+ lines.push(`${key}: ${typeof val === 'object' ? JSON.stringify(val) : val}`);
533
+ }
534
+ return lines.join('\n');
535
+ }
536
+
472
537
  // Format output data (returns string, does not print)
473
538
  export function formatOutput(data, { pretty = false, table = false, csv = false } = {}) {
474
- if (csv) {
475
- if (data.success === false) {
476
- return { type: 'error', text: `Error: ${data.error}` };
477
- }
478
- const csvData = data.data || data;
479
- return { type: 'csv', text: formatCsv(csvData) };
480
- } else if (table) {
539
+ if (csv || table) {
481
540
  if (data.success === false) {
482
- return { type: 'error', text: `Error: ${data.error}` };
483
- } else {
484
- const tableData = data.data || data;
485
- return { type: 'table', text: formatTable(tableData) };
541
+ return { type: 'error', text: formatErrorText(data, { csv }) };
486
542
  }
543
+ const body = data.data || data;
544
+ return csv
545
+ ? { type: 'csv', text: formatCsv(body) }
546
+ : { type: 'table', text: formatTable(body) };
487
547
  } else if (pretty) {
488
548
  return { type: 'json', text: JSON.stringify(data, null, 2) };
489
549
  } else {
@@ -500,6 +560,10 @@ export const USAGE_ERROR_CODES = new Set(['MISSING_PARAM', 'MISSING_ARGS']);
500
560
 
501
561
  export function isUsageError(errorData, { pretty, table, csv, stream, isTTY }) {
502
562
  if (!USAGE_ERROR_CODES.has(errorData.code)) return false;
563
+ // API errors can map onto the same semantic code (for example the server's
564
+ // `missing_field` becomes MISSING_PARAM), but they are not local usage
565
+ // banners and must retain the structured envelope in every output mode.
566
+ if (errorData.status != null) return false;
503
567
  if (pretty || table || csv || stream) return false;
504
568
  return !!isTTY;
505
569
  }
@@ -849,47 +913,102 @@ export async function compareWallets(api, params = {}) {
849
913
  }
850
914
  }
851
915
 
852
- // Fetch counterparties and balances for both addresses
916
+ // Fetch counterparties and balances for both addresses. A failed request is
917
+ // recorded rather than treated as an empty result, so an auth or rate-limit
918
+ // error cannot masquerade as "no overlap" / "0 USD".
919
+ const settle = (promise) => promise.then(value => ({ value }), error => ({ error }));
853
920
  const [cp1, cp2] = await Promise.all([
854
- api.addressCounterparties({ address: addr1, chain, days }).catch(() => null),
855
- api.addressCounterparties({ address: addr2, chain, days }).catch(() => null),
921
+ settle(api.addressCounterparties({ address: addr1, chain, days })),
922
+ settle(api.addressCounterparties({ address: addr2, chain, days })),
856
923
  ]);
857
924
  await sleep(delayMs);
858
925
  const [bal1, bal2] = await Promise.all([
859
- api.addressBalance({ address: addr1, chain }).catch(() => null),
860
- api.addressBalance({ address: addr2, chain }).catch(() => null),
926
+ settle(api.addressBalance({ address: addr1, chain })),
927
+ settle(api.addressBalance({ address: addr2, chain })),
861
928
  ]);
862
929
 
930
+ const outcomes = [
931
+ [addr1, 'counterparties', cp1], [addr2, 'counterparties', cp2],
932
+ [addr1, 'balance', bal1], [addr2, 'balance', bal2],
933
+ ];
934
+ const errors = [];
935
+ const failures = [];
936
+ for (const [address, source, outcome] of outcomes) {
937
+ if (outcome.error) {
938
+ failures.push(outcome.error);
939
+ errors.push({ address, source, code: outcome.error.code ?? 'UNKNOWN', message: outcome.error.message });
940
+ }
941
+ }
942
+ if (failures.length === outcomes.length) {
943
+ throw failures[0];
944
+ }
945
+
863
946
  // Extract counterparty addresses
864
947
  const extractCps = (result) => {
865
948
  const list = result?.data?.results || result?.counterparties || result?.data || [];
866
949
  return Array.isArray(list) ? list : [];
867
950
  };
868
- const cps1 = extractCps(cp1);
869
- const cps2 = extractCps(cp2);
870
- const cpAddrs1 = new Set(cps1.map(c => c.counterparty_address || c.address || c.counterparty).filter(Boolean));
871
- const cpAddrs2 = new Set(cps2.map(c => c.counterparty_address || c.address || c.counterparty).filter(Boolean));
872
- const sharedCpAddrs = [...cpAddrs1].filter(a => cpAddrs2.has(a));
951
+ let sharedCpAddrs = null;
952
+ if (!cp1.error && !cp2.error) {
953
+ const cpAddrs1 = new Set(extractCps(cp1.value).map(c => c.counterparty_address || c.address || c.counterparty).filter(Boolean));
954
+ const cpAddrs2 = new Set(extractCps(cp2.value).map(c => c.counterparty_address || c.address || c.counterparty).filter(Boolean));
955
+ sharedCpAddrs = [...cpAddrs1].filter(a => cpAddrs2.has(a));
956
+ }
873
957
 
874
958
  // Extract token holdings
875
959
  const extractTokens = (result) => {
876
960
  const list = result?.data?.results || result?.balances || result?.data || [];
877
961
  return Array.isArray(list) ? list : [];
878
962
  };
879
- const tokens1 = extractTokens(bal1);
880
- const tokens2 = extractTokens(bal2);
881
- const tokenSyms1 = new Set(tokens1.map(t => t.token_symbol).filter(Boolean));
882
- const tokenSyms2 = new Set(tokens2.map(t => t.token_symbol).filter(Boolean));
883
- const sharedTokens = [...tokenSyms1].filter(s => tokenSyms2.has(s));
963
+ const tokens1 = bal1.error ? null : extractTokens(bal1.value);
964
+ const tokens2 = bal2.error ? null : extractTokens(bal2.value);
965
+ let sharedTokens = null;
966
+ if (tokens1 && tokens2) {
967
+ // Two different contracts can share a symbol, so when both sides report a
968
+ // token address the address decides. When either side has no address for
969
+ // a token (some responses omit it for the native asset) the symbol is the
970
+ // only identity available and is used instead.
971
+ const addressOf = (t) => {
972
+ const address = t.token_address || t.mint || t.address;
973
+ return address ? String(address).toLowerCase() : null;
974
+ };
975
+ const symbolOf = (t) => (t.token_symbol ? String(t.token_symbol).toLowerCase() : null);
976
+ const addresses2 = new Set(tokens2.map(addressOf).filter(Boolean));
977
+ const symbols2 = new Set(tokens2.map(symbolOf).filter(Boolean));
978
+ const symbolsWithoutAddress2 = new Set(
979
+ tokens2.filter(t => !addressOf(t)).map(symbolOf).filter(Boolean)
980
+ );
981
+ const seen = new Set();
982
+ sharedTokens = [];
983
+ for (const t of tokens1) {
984
+ const address = addressOf(t);
985
+ const symbol = symbolOf(t);
986
+ // With an address on both sides only the address counts. If either
987
+ // side omits it (as some responses do for the native asset) a matching
988
+ // symbol is taken as the same token.
989
+ const matched = address
990
+ ? addresses2.has(address) || (symbol && symbolsWithoutAddress2.has(symbol))
991
+ : symbol && symbols2.has(symbol);
992
+ const key = address || symbol;
993
+ if (matched && !seen.has(key)) {
994
+ seen.add(key);
995
+ sharedTokens.push(t.token_symbol || address);
996
+ }
997
+ }
998
+ }
999
+ const totalUsd = (tokens) => tokens === null
1000
+ ? null
1001
+ : tokens.reduce((sum, t) => sum + (t.value_usd ?? t.balance_usd ?? 0), 0);
884
1002
 
885
1003
  return {
886
1004
  addresses: [addr1, addr2], chain,
887
1005
  shared_counterparties: sharedCpAddrs,
888
1006
  shared_tokens: sharedTokens,
889
1007
  balances: [
890
- { address: addr1, total_usd: tokens1.reduce((sum, t) => sum + (t.value_usd ?? t.balance_usd ?? 0), 0) },
891
- { address: addr2, total_usd: tokens2.reduce((sum, t) => sum + (t.value_usd ?? t.balance_usd ?? 0), 0) },
1008
+ { address: addr1, total_usd: totalUsd(tokens1) },
1009
+ { address: addr2, total_usd: totalUsd(tokens2) },
892
1010
  ],
1011
+ ...(errors.length > 0 && { incomplete: true, errors }),
893
1012
  };
894
1013
  }
895
1014
 
@@ -902,9 +1021,9 @@ USAGE: nansen <command> [subcommand] [options]
902
1021
  COMMANDS:
903
1022
  trade DEX swaps/bridges: quote, execute, bridge-status, limit-order
904
1023
  bridge Hyperliquid bridge: quote, execute, status (EVM <-> HL)
905
- perp Hyperliquid perps: order, cancel, close, leverage, positions
1024
+ perp Hyperliquid perps: order, cancel, close, leverage, transfer, approve-builder-fee, positions, orders, account, meta, screener, leaderboard
906
1025
  research analytics: smart-money, profiler, token, search, perp, portfolio
907
- wallet create, list, show, export, default, delete, forget-password
1026
+ wallet ${WALLET_SUBCOMMANDS.join(', ')}
908
1027
  agent Ask the Nansen AI research agent (fast/expert modes)
909
1028
  alerts list, create, update, toggle, delete
910
1029
  web search, fetch
@@ -944,10 +1063,10 @@ EXAMPLES:
944
1063
  nansen research profiler balance --address 0x... --chain ethereum
945
1064
 
946
1065
  DEPRECATED ALIASES (still work, will be removed in a future version):
947
- smart-money, profiler, token, search, perp, portfolio → use "nansen research <command>"
1066
+ smart-money, profiler, token, search, portfolio → use "nansen research <command>"
948
1067
  quote, execute → use "nansen trade <command>"
949
1068
 
950
- Research chains: ethereum, solana, base, bnb, arbitrum, polygon, optimism, avalanche, linea, scroll, mantle, ronin, sei, plasma, sonic, monad, hyperevm, iotaevm
1069
+ Research chains: ${SCHEMA.chains.join(', ')}
951
1070
  Trade chains: solana, base
952
1071
  Bridge chains: ethereum, base, arbitrum, polygon, bnb, hyperliquid
953
1072
  Labels: Fund, Smart Trader, 30D/90D/180D Smart Trader, Smart HL Perps Trader
@@ -972,7 +1091,7 @@ SUBCOMMANDS:
972
1091
  USAGE:
973
1092
  nansen trade quote --chain <chain> --from <token> --to <token> --amount <units> [--wallet <name>]
974
1093
  nansen trade quote --chain <chain> --to-chain <chain> --from <token> --to <token> --amount <units>
975
- nansen trade execute --quote <quoteId> [--wallet <name>]
1094
+ nansen trade execute --quote <quoteId> [--wallet <name>] [--dry-run] [--yes]
976
1095
  nansen trade bridge-status --tx-hash <hash> --from-chain <chain> --to-chain <chain>
977
1096
  nansen trade limit-order <create|list|cancel|update> [options]
978
1097
 
@@ -989,6 +1108,13 @@ WALLET:
989
1108
  --wallet <name> Use a named wallet, or "walletconnect" / "wc" for WalletConnect.
990
1109
  Defaults to the default local wallet if omitted.
991
1110
 
1111
+ BEFORE BROADCASTING (execute only):
1112
+ --dry-run Validate and print what would be sent, then stop. Nothing is
1113
+ signed or broadcast and the quote stays usable. Exits 0.
1114
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1). The prompt
1115
+ only appears when stdin is a terminal — agents, CI and pipes run
1116
+ unprompted either way. Declining exits 1 with nothing signed.
1117
+
992
1118
  SYMBOLS:
993
1119
  Common tokens resolve automatically: SOL, ETH, USDC, USDT, WETH
994
1120
  Raw addresses are also accepted.
@@ -1051,12 +1177,43 @@ export async function prompt(question, hidden = false, { input = process.stdin,
1051
1177
  });
1052
1178
  }
1053
1179
 
1180
+ // Confirmation prompts belong to the CLI adapter rather than trade/bridge
1181
+ // core. EOF and Ctrl+C resolve as the safe default ("no") so a closed input
1182
+ // cannot leave an irreversible command hanging forever.
1183
+ export async function promptForConfirmation(question, { input = process.stdin, output = process.stderr } = {}) {
1184
+ const rl = readline.createInterface({ input, output });
1185
+ return new Promise((resolve, reject) => {
1186
+ let settled = false;
1187
+ const finish = (answer) => {
1188
+ if (settled) return;
1189
+ settled = true;
1190
+ rl.close();
1191
+ resolve(answer);
1192
+ };
1193
+ const fail = (error) => {
1194
+ if (settled) return;
1195
+ settled = true;
1196
+ rl.close();
1197
+ reject(error);
1198
+ };
1199
+
1200
+ rl.once('close', () => finish(''));
1201
+ rl.once('SIGINT', () => finish(''));
1202
+ rl.once('error', fail);
1203
+ rl.question(question, finish);
1204
+ });
1205
+ }
1206
+
1054
1207
  // Build command handlers (returns object with handler functions)
1055
1208
  export function buildCommands(deps = {}) {
1056
1209
  // Allow dependency injection for testing
1057
1210
  const {
1058
1211
  api: _api = null,
1212
+ // Password/API-key input belongs to login and may be hidden. Confirmation
1213
+ // is a separate contract: callers must opt into it explicitly so this
1214
+ // prompt can never be reused for an irreversible yes/no decision.
1059
1215
  promptFn = prompt,
1216
+ confirmationPromptFn,
1060
1217
  log = console.log,
1061
1218
  errorOutput: _errorOutput = console.error,
1062
1219
  NansenAPIClass: _NansenAPIClass = NansenAPI,
@@ -1121,14 +1278,9 @@ export function buildCommands(deps = {}) {
1121
1278
  throw new NansenError('At least one query is required. Usage: nansen web search "bitcoin price" --num-results 5', ErrorCode.MISSING_PARAM);
1122
1279
  }
1123
1280
  let numResults;
1124
- if (options['num-results'] !== undefined) {
1125
- const numResultsRaw = parseInt(options['num-results'], 10);
1126
- if (Number.isNaN(numResultsRaw)) {
1127
- // Non-numeric — fall back to API default
1128
- numResults = undefined;
1129
- } else if (numResultsRaw >= 1 && numResultsRaw <= 20) {
1130
- numResults = numResultsRaw;
1131
- } else {
1281
+ if (options['num-results'] !== undefined || flags['num-results']) {
1282
+ numResults = parseSafeIntegerOption('num-results', options, flags, undefined, 'whole number between 1 and 20');
1283
+ if (numResults < 1 || numResults > 20) {
1132
1284
  throw new NansenError('--num-results must be between 1 and 20', ErrorCode.INVALID_PARAMS);
1133
1285
  }
1134
1286
  }
@@ -1320,8 +1472,10 @@ export function buildCommands(deps = {}) {
1320
1472
  // silently comparing as if it were version 0.0.0, which would show
1321
1473
  // every entry rather than flag the typo.
1322
1474
  if (!/^v?\d+(\.\d+){0,2}$/.test(String(since))) {
1323
- log(`Invalid --since value "${since}": expected a version like 1.43 or 1.43.0.`);
1324
- return;
1475
+ throw new NansenError(
1476
+ `Invalid --since value "${since}": expected a version like 1.43 or 1.43.0.`,
1477
+ ErrorCode.INVALID_PARAMS
1478
+ );
1325
1479
  }
1326
1480
  // Show only entries from the given version onwards
1327
1481
  const lines = content.split('\n');
@@ -1404,7 +1558,7 @@ export function buildCommands(deps = {}) {
1404
1558
  const subcommand = args[0] || 'help';
1405
1559
  const chain = options.chain || 'solana';
1406
1560
  const chains = options.chains || [chain];
1407
- const filters = options.filters || {};
1561
+ const filters = parseObjectOption(options.filters, 'filters');
1408
1562
  const orderBy = parseSort(options.sort, options['order-by']);
1409
1563
  const pagination = buildPagination(options);
1410
1564
 
@@ -1422,7 +1576,7 @@ export function buildCommands(deps = {}) {
1422
1576
  const handlers = {
1423
1577
  'netflow': () => apiInstance.smartMoneyNetflow({ chains, filters, orderBy, pagination }),
1424
1578
  'dex-trades': () => apiInstance.smartMoneyDexTrades({ chains, filters, orderBy, pagination }),
1425
- 'perp-trades': () => apiInstance.smartMoneyPerpTrades({ filters, orderBy, pagination, onlyNewPositions: options['only-new-positions'] ?? flags['only-new-positions'] }),
1579
+ 'perp-trades': () => apiInstance.smartMoneyPerpTrades({ filters, orderBy, pagination, onlyNewPositions: resolveBooleanOption(options, flags, 'only-new-positions') }),
1426
1580
  'holdings': () => apiInstance.smartMoneyHoldings({ chains, filters, orderBy, pagination }),
1427
1581
  'dcas': () => apiInstance.smartMoneyDcas({ filters, orderBy, pagination }),
1428
1582
  'historical-holdings': () => apiInstance.smartMoneyHistoricalHoldings({ chains, filters, orderBy, pagination, days }),
@@ -1460,7 +1614,7 @@ export function buildCommands(deps = {}) {
1460
1614
  throw new NansenError(err.message, ErrorCode.INVALID_ADDRESS);
1461
1615
  }
1462
1616
  }
1463
- const filters = options.filters || {};
1617
+ const filters = parseObjectOption(options.filters, 'filters');
1464
1618
  const orderBy = parseSort(options.sort, options['order-by']);
1465
1619
  const pagination = buildPagination(options);
1466
1620
  const days = [
@@ -1520,7 +1674,7 @@ export function buildCommands(deps = {}) {
1520
1674
  }
1521
1675
  const parsedInclude = parseCsvOption(options.include, 'include');
1522
1676
  const include = (parsedInclude && parsedInclude.length > 0) ? parsedInclude : ['labels', 'balance'];
1523
- const delayMs = options.delay ? parseInt(options.delay) : 1000;
1677
+ const delayMs = parseNonNegativeSafeIntegerOption('delay', options, flags, 1000);
1524
1678
  return batchProfile(apiInstance, { addresses, chain, include, delayMs });
1525
1679
  },
1526
1680
  'trace': () => {
@@ -1534,7 +1688,7 @@ export function buildCommands(deps = {}) {
1534
1688
  }
1535
1689
  const depth = options.depth ?? 2;
1536
1690
  const width = parseNonNegativeSafeIntegerOption('width', options, flags, 10);
1537
- const delayMs = options.delay ? parseInt(options.delay) : 1000;
1691
+ const delayMs = parseNonNegativeSafeIntegerOption('delay', options, flags, 1000);
1538
1692
  return traceCounterparties(apiInstance, { address, chain, depth, width, days, delayMs });
1539
1693
  },
1540
1694
  'compare': () => {
@@ -1572,7 +1726,7 @@ export function buildCommands(deps = {}) {
1572
1726
  const tokenSymbol = options.symbol || options['token-symbol'];
1573
1727
  const chains = options.chains || [chain];
1574
1728
  const timeframe = options.timeframe || '24h';
1575
- const filters = options.filters || {};
1729
+ const filters = parseObjectOption(options.filters, 'filters');
1576
1730
  const orderBy = parseSort(options.sort, options['order-by']);
1577
1731
  const pagination = buildPagination(options);
1578
1732
  const days = [
@@ -1588,13 +1742,13 @@ export function buildCommands(deps = {}) {
1588
1742
  : 30;
1589
1743
 
1590
1744
  // Convenience filter for smart money only
1591
- const onlySmartMoney = options['smart-money'] || flags['smart-money'] || false;
1745
+ const onlySmartMoney = resolveBooleanOption(options, flags, 'smart-money') ?? false;
1592
1746
  if (onlySmartMoney) {
1593
1747
  filters.include_smart_money_labels = filters.include_smart_money_labels ||
1594
1748
  ['Fund', 'Smart Trader', '30D Smart Trader', '90D Smart Trader', '180D Smart Trader'];
1595
1749
  }
1596
1750
 
1597
- const includeStablecoins = options['include-stablecoins'] ?? flags['include-stablecoins'];
1751
+ const includeStablecoins = resolveBooleanOption(options, flags, 'include-stablecoins');
1598
1752
  if (includeStablecoins !== undefined) {
1599
1753
  filters.include_stablecoins = includeStablecoins;
1600
1754
  }
@@ -1605,19 +1759,26 @@ export function buildCommands(deps = {}) {
1605
1759
  'info': () => apiInstance.tokenInformation({ tokenAddress, chain, timeframe: options.timeframe }),
1606
1760
  'screener': async () => {
1607
1761
  const search = options.search;
1608
- // When searching, fetch more results to filter from (API has no server-side search)
1609
- const searchPagination = search
1610
- ? { page: 1, per_page: Math.max(500, pagination?.per_page || 0) }
1762
+ if (search !== undefined && typeof search !== 'string') {
1763
+ throw new NansenError('--search must be a string', ErrorCode.INVALID_PARAMS);
1764
+ }
1765
+ // When searching, fetch more results to filter from (API has no server-side search).
1766
+ // --page/--limit are applied client-side to the filtered list, so the
1767
+ // candidate fetch has to cover every page up to the requested one.
1768
+ const requestedLimit = pagination?.per_page || 100;
1769
+ const requestedPage = pagination?.page || 1;
1770
+ const searchPagination = search
1771
+ ? { page: 1, per_page: Math.max(500, requestedPage * requestedLimit) }
1611
1772
  : pagination;
1612
1773
  const result = await apiInstance.tokenScreener({ chains, timeframe, filters, orderBy, pagination: searchPagination });
1613
1774
  if (search) {
1614
1775
  const q = search.toLowerCase();
1615
- const requestedLimit = pagination?.per_page || 100;
1776
+ const offset = (requestedPage - 1) * requestedLimit;
1616
1777
  const filterArr = (arr) => arr.filter(t =>
1617
1778
  (t.token_symbol && t.token_symbol.toLowerCase().includes(q)) ||
1618
1779
  (t.token_name && t.token_name.toLowerCase().includes(q)) ||
1619
1780
  (t.token_address && t.token_address.toLowerCase() === q)
1620
- ).slice(0, requestedLimit);
1781
+ ).slice(offset, offset + requestedLimit);
1621
1782
  // Handle nested response shapes: {data: [...]} or {data: {data: [...]}}
1622
1783
  if (Array.isArray(result?.data)) {
1623
1784
  return { ...result, data: filterArr(result.data) };
@@ -1640,7 +1801,14 @@ export function buildCommands(deps = {}) {
1640
1801
  },
1641
1802
  'who-bought-sold': () => {
1642
1803
  const date = parseDateOption(options.date, days, flags.date);
1643
- const buyOrSell = (options['buy-or-sell'] || 'BUY').toUpperCase();
1804
+ const buyOrSellRaw = options['buy-or-sell'];
1805
+ if (buyOrSellRaw !== undefined && typeof buyOrSellRaw !== 'string') {
1806
+ throw new NansenError('--buy-or-sell must be BUY or SELL', ErrorCode.INVALID_PARAMS);
1807
+ }
1808
+ const buyOrSell = (buyOrSellRaw || 'BUY').toUpperCase();
1809
+ if (buyOrSell !== 'BUY' && buyOrSell !== 'SELL') {
1810
+ throw new NansenError('--buy-or-sell must be BUY or SELL', ErrorCode.INVALID_PARAMS);
1811
+ }
1644
1812
  return apiInstance.tokenWhoBoughtSold({ tokenAddress, chain, buyOrSell, filters, orderBy, pagination, days, date });
1645
1813
  },
1646
1814
  'flow-intelligence': () => apiInstance.tokenFlowIntelligence({ tokenAddress, chain, timeframe: options.timeframe || '1d' }),
@@ -1659,7 +1827,7 @@ export function buildCommands(deps = {}) {
1659
1827
  },
1660
1828
  'top-tokens': () => {
1661
1829
  const marketCapGroup = options['market-cap'] || options['market-cap-group'];
1662
- const limit = options.limit ? parseInt(options.limit) : undefined;
1830
+ const limit = parseNonNegativeSafeIntegerOption('limit', options, flags);
1663
1831
  return apiInstance.topTokens({ marketCapGroup, limit });
1664
1832
  },
1665
1833
  'help': () => ({
@@ -1729,7 +1897,7 @@ export function buildCommands(deps = {}) {
1729
1897
  'perp': async (args, apiInstance, flags, options) => {
1730
1898
  rejectBlankOption(options.days, 'days', '30');
1731
1899
  const subcommand = args[0] || 'help';
1732
- const filters = options.filters || {};
1900
+ const filters = parseObjectOption(options.filters, 'filters');
1733
1901
  const orderBy = parseSort(options.sort, options['order-by']);
1734
1902
  const pagination = buildPagination(options);
1735
1903
  const days = ['screener', 'leaderboard'].includes(subcommand)
@@ -1874,7 +2042,8 @@ export function buildCommands(deps = {}) {
1874
2042
  };
1875
2043
 
1876
2044
  // 'trade' delegates to quote/execute from buildTradingCommands and limit-order from buildLimitOrderCommands
1877
- const tradingCmds = buildTradingCommands(deps);
2045
+ const executionDeps = { ...deps, promptFn: confirmationPromptFn };
2046
+ const tradingCmds = buildTradingCommands(executionDeps);
1878
2047
  const limitOrderCmds = buildLimitOrderCommands(deps);
1879
2048
  cmds['trade'] = async (args, apiInstance, flags, options) => {
1880
2049
  const sub = args[0];
@@ -1912,7 +2081,7 @@ USAGE:
1912
2081
  };
1913
2082
 
1914
2083
  // 'bridge' delegates to quote/execute/status from buildBridgeCommands
1915
- const bridgeCmds = buildBridgeCommands(deps);
2084
+ const bridgeCmds = buildBridgeCommands(executionDeps);
1916
2085
  cmds['bridge'] = async (args, apiInstance, flags, options) => {
1917
2086
  const sub = args[0];
1918
2087
  if (!sub || sub === 'help') {
@@ -1925,9 +2094,14 @@ SUBCOMMANDS:
1925
2094
 
1926
2095
  USAGE:
1927
2096
  nansen bridge quote --from-chain base --to-chain hyperliquid --from-token USDC --amount 1000000
1928
- nansen bridge execute --quote <quoteId>
2097
+ nansen bridge execute --quote <quoteId> [--dry-run] [--yes]
1929
2098
  nansen bridge status --request-id <id>
1930
2099
 
2100
+ BEFORE BROADCASTING (execute only):
2101
+ --dry-run Validate and print what would be signed, then stop. Exits 0.
2102
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1). The prompt only
2103
+ appears when stdin is a terminal; declining exits 1, signing nothing.
2104
+
1931
2105
  SUPPORTED ROUTES:
1932
2106
  ${formatBridgeRoutes()}`);
1933
2107
  return;
@@ -2011,7 +2185,16 @@ export const RESEARCH_CATEGORY_ALIASES = {
2011
2185
 
2012
2186
  // Generate help text for a specific subcommand using SCHEMA
2013
2187
  export function generateSubcommandHelp(command, subcommand, prefix = null) {
2014
- const cmdSchema = SCHEMA.commands[command] || SCHEMA.commands.research.subcommands[command];
2188
+ // `perp` is both a top-level trading command and a research category, and
2189
+ // the two have different subcommands. Look in both places and use whichever
2190
+ // actually holds this subcommand (top-level wins when both do) instead of
2191
+ // stopping at the first schema whose *name* matches — that made
2192
+ // `research perp screener --help` fall back to listing the category's
2193
+ // subcommands, i.e. telling the caller to run the command they just ran.
2194
+ const topSchema = SCHEMA.commands[command];
2195
+ const researchSchema = SCHEMA.commands.research.subcommands[command];
2196
+ const fromResearch = !topSchema?.subcommands?.[subcommand] && Boolean(researchSchema?.subcommands?.[subcommand]);
2197
+ const cmdSchema = fromResearch ? researchSchema : topSchema || researchSchema;
2015
2198
  if (!cmdSchema) return null;
2016
2199
 
2017
2200
  const subSchema = cmdSchema.subcommands?.[subcommand];
@@ -2042,7 +2225,7 @@ export function generateSubcommandHelp(command, subcommand, prefix = null) {
2042
2225
 
2043
2226
  const exampleValues = { address: '0x...', token: '0x...', query: '"term"', symbol: 'BTC', date: '2024-01-01' };
2044
2227
  const chain = subSchema.options?.chain?.default || 'solana';
2045
- const cmdPrefix = prefix || (DEPRECATED_TO_RESEARCH.has(command) ? `research ${command}` : command);
2228
+ const cmdPrefix = prefix || (fromResearch || DEPRECATED_TO_RESEARCH.has(command) ? `research ${command}` : command);
2046
2229
  let example = subSchema.examples?.[0] || `nansen ${cmdPrefix} ${subcommand}`;
2047
2230
  if (!subSchema.examples?.length && subSchema.options) {
2048
2231
  for (const [name, opt] of Object.entries(subSchema.options)) {
@@ -2065,12 +2248,45 @@ export async function runCLI(rawArgs, deps = {}) {
2065
2248
  exit = process.exit,
2066
2249
  NansenAPIClass = NansenAPI,
2067
2250
  commandOverrides = {},
2068
- // Injectable so tests can exercise both renderings; defaults to the real
2069
- // terminal, which is false under a pipe or in CI.
2251
+ // Output TTY controls human-vs-structured error rendering. Keep the
2252
+ // existing `isTTY` seam for callers/tests that inject both terminal states.
2070
2253
  isTTY = process.stdout.isTTY,
2071
2254
  } = deps;
2072
2255
 
2073
- const { _: positional, flags, options } = parseArgs(rawArgs);
2256
+ // Command-layer interactivity is intentionally governed by stdin. Besides
2257
+ // trade/bridge confirmation, buildCommands' existing `login --human` prompt
2258
+ // consumes this same signal; stdout may be redirected while a person still
2259
+ // answers either prompt on stdin. The separate `isTTY` destructured above
2260
+ // remains the stdout signal for human-vs-structured error rendering. Callers
2261
+ // can split the signals with `isInputTTY`; legacy `isTTY` injection still
2262
+ // drives both for compatibility.
2263
+ const isInputTTY = deps.isInputTTY ?? (deps.isTTY ?? process.stdin.isTTY);
2264
+
2265
+ // Pass the CLI-owned terminal seams into command modules. Keeping these out
2266
+ // of core means direct/library callers are non-interactive unless they
2267
+ // explicitly provide a prompt.
2268
+ const inputInteractiveDeps = {
2269
+ ...deps,
2270
+ isTTY: isInputTTY,
2271
+ promptFn: deps.promptFn ?? prompt,
2272
+ confirmationPromptFn: deps.confirmationPromptFn ?? promptForConfirmation,
2273
+ confirmationLog: deps.confirmationLog ?? errorOutput,
2274
+ };
2275
+ const topLevelTradingDeps = {
2276
+ ...inputInteractiveDeps,
2277
+ promptFn: inputInteractiveDeps.confirmationPromptFn,
2278
+ };
2279
+
2280
+ let parsed;
2281
+ try {
2282
+ parsed = parseArgs(rawArgs);
2283
+ } catch (error) {
2284
+ const errorData = formatError(error);
2285
+ output(formatOutput(errorData).text);
2286
+ exit(1);
2287
+ return { type: 'error', data: errorData };
2288
+ }
2289
+ const { _: positional, flags, options } = parsed;
2074
2290
 
2075
2291
  // Resolve command aliases
2076
2292
  const rawCommand = positional[0] || 'help';
@@ -2113,7 +2329,11 @@ export async function runCLI(rawArgs, deps = {}) {
2113
2329
 
2114
2330
  // mcp prints its own output via `log`; runCLI callers inject their stdout
2115
2331
  // sink as `output`, so map it across (an explicit `log` dep still wins).
2116
- const commands = { ...buildCommands(deps), ...buildWalletCommands(deps), ...buildTradingCommands(deps), ...buildAlertsCommands(deps), ...buildAgentCommands(deps), ...buildMcpCommands({ ...deps, log: deps.log ?? output }), ...buildCompletionCommands({ ...deps, log: deps.log ?? output }), ...commandOverrides };
2332
+ // Only execute/login handlers consume the stdin-interactivity seam. Other
2333
+ // modules retain their existing deps: notably wallet export interprets
2334
+ // `isTTY` as stdout visibility when deciding whether to warn about printing
2335
+ // private keys, so substituting the stdin signal there changes its semantics.
2336
+ const commands = { ...buildCommands(inputInteractiveDeps), ...buildWalletCommands(deps), ...buildTradingCommands(topLevelTradingDeps), ...buildAlertsCommands(deps), ...buildAgentCommands(deps), ...buildMcpCommands({ ...deps, log: deps.log ?? output }), ...buildCompletionCommands({ ...deps, log: deps.log ?? output }), ...commandOverrides };
2117
2337
 
2118
2338
  if (flags.version || flags.v) {
2119
2339
  output(VERSION);