nansen-cli 1.44.3 → 1.45.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.
@@ -4,6 +4,7 @@
4
4
  */
5
5
 
6
6
  import { NansenError, ErrorCode } from '../api.js';
7
+ import { parseCsvOption } from '../query-options.js';
7
8
 
8
9
  // ============= Formatting =============
9
10
 
@@ -53,10 +54,13 @@ export function formatAlertsTable(alerts) {
53
54
  * Parse a token string "address:chain" into { address, chain }.
54
55
  * Handles single string or array of strings (from repeated --token flags).
55
56
  */
56
- function parseTokens(tokenArg) {
57
- if (!tokenArg) return undefined;
57
+ function parseTokens(tokenArg, name) {
58
+ if (tokenArg === undefined || tokenArg === '') return undefined;
58
59
  const tokens = Array.isArray(tokenArg) ? tokenArg : [tokenArg];
59
60
  return tokens.map(t => {
61
+ if (typeof t !== 'string') {
62
+ throw new NansenError(`--${name} values must be strings`, ErrorCode.INVALID_PARAMS);
63
+ }
60
64
  const colonIdx = t.lastIndexOf(':');
61
65
  if (colonIdx === -1) throw new NansenError(`Invalid token format: "${t}". Expected address:chain`, ErrorCode.INVALID_PARAMS);
62
66
  return { address: t.slice(0, colonIdx), chain: t.slice(colonIdx + 1) };
@@ -67,10 +71,13 @@ function parseTokens(tokenArg) {
67
71
  * Parse a subject string "type:value" into { type, value }.
68
72
  * Handles single string or array (from repeated --subject flags).
69
73
  */
70
- function parseSubjects(subjectArg) {
71
- if (!subjectArg) return undefined;
74
+ function parseSubjects(subjectArg, name) {
75
+ if (subjectArg === undefined || subjectArg === '') return undefined;
72
76
  const subjects = Array.isArray(subjectArg) ? subjectArg : [subjectArg];
73
77
  return subjects.map(s => {
78
+ if (typeof s !== 'string') {
79
+ throw new NansenError(`--${name} values must be strings`, ErrorCode.INVALID_PARAMS);
80
+ }
74
81
  const colonIdx = s.indexOf(':');
75
82
  if (colonIdx === -1) throw new NansenError(`Invalid subject format: "${s}". Expected type:value`, ErrorCode.INVALID_PARAMS);
76
83
  return { type: s.slice(0, colonIdx), value: s.slice(colonIdx + 1) };
@@ -102,9 +109,7 @@ function deepMergePlain(target, source) {
102
109
  * Normalise chains option to array.
103
110
  */
104
111
  function parseChains(chainsOpt) {
105
- if (!chainsOpt) return undefined;
106
- if (Array.isArray(chainsOpt)) return chainsOpt;
107
- return chainsOpt.split(',').map(s => s.trim()).filter(Boolean);
112
+ return parseCsvOption(chainsOpt, 'chains');
108
113
  }
109
114
 
110
115
  /**
@@ -124,6 +129,21 @@ function parseFiniteNumber(raw, name) {
124
129
  return n;
125
130
  }
126
131
 
132
+ /**
133
+ * Validate a single-value string filter option (e.g. --chain, --token-address).
134
+ * Empty string/undefined mean "not provided"; any other non-string value
135
+ * (e.g. `--chain true`, from parseArgs' JSON.parse of option values) is
136
+ * rejected instead of crashing on .toLowerCase() or being silently dropped
137
+ * by a falsy check.
138
+ */
139
+ function parseStringFilter(val, name) {
140
+ if (val === undefined || val === '') return undefined;
141
+ if (typeof val !== 'string') {
142
+ throw new NansenError(`--${name} must be a string`, ErrorCode.INVALID_PARAMS);
143
+ }
144
+ return val;
145
+ }
146
+
127
147
  function parseNonNegativeIntegerOption(raw, name) {
128
148
  if (raw === undefined) return undefined;
129
149
  const n = Number(raw);
@@ -145,14 +165,6 @@ function buildRange(minVal, maxVal, name) {
145
165
  return r;
146
166
  }
147
167
 
148
- /**
149
- * Normalise a repeatable string option to array, or undefined if absent.
150
- */
151
- function normArray(val) {
152
- if (!val) return undefined;
153
- return Array.isArray(val) ? val : [val];
154
- }
155
-
156
168
  /**
157
169
  * Build the data payload for sm-token-flows alerts from named flags.
158
170
  */
@@ -171,14 +183,14 @@ export function buildSmTokenFlowsData(options) {
171
183
  }
172
184
  }
173
185
 
174
- const tokens = parseTokens(options.token);
175
- const excludeTokens = parseTokens(options['exclude-token']);
186
+ const tokens = parseTokens(options.token, 'token');
187
+ const excludeTokens = parseTokens(options['exclude-token'], 'exclude-token');
176
188
  if (tokens) data.inclusion = { ...data.inclusion, tokens };
177
189
  if (excludeTokens) data.exclusion = { ...data.exclusion, tokens: excludeTokens };
178
190
 
179
- const sectors = normArray(options['token-sector']);
191
+ const sectors = parseCsvOption(options['token-sector'], 'token-sector');
180
192
  if (sectors) data.inclusion = { ...data.inclusion, tokenSectors: sectors };
181
- const excludeSectors = normArray(options['exclude-token-sector']);
193
+ const excludeSectors = parseCsvOption(options['exclude-token-sector'], 'exclude-token-sector');
182
194
  if (excludeSectors) data.exclusion = { ...data.exclusion, tokenSectors: excludeSectors };
183
195
 
184
196
  if (options['token-age-max'] !== undefined) {
@@ -203,9 +215,8 @@ export function buildCommonTokenTransferData(options) {
203
215
  const chains = parseChains(options.chains);
204
216
  if (chains) data.chains = chains;
205
217
 
206
- if (options.events) {
207
- data.events = typeof options.events === 'string' ? options.events.split(',') : options.events;
208
- }
218
+ const events = parseCsvOption(options.events, 'events');
219
+ if (events) data.events = events;
209
220
 
210
221
  const usdRange = buildRange(options['usd-min'], options['usd-max'], 'usd');
211
222
  if (usdRange) data.usdValue = usdRange;
@@ -213,20 +224,20 @@ export function buildCommonTokenTransferData(options) {
213
224
  const amountRange = buildRange(options['token-amount-min'], options['token-amount-max'], 'token-amount');
214
225
  if (amountRange) data.tokenAmount = amountRange;
215
226
 
216
- const subjects = parseSubjects(options.subject);
227
+ const subjects = parseSubjects(options.subject, 'subject');
217
228
  if (subjects) data.subjects = subjects;
218
229
 
219
- const counterparties = parseSubjects(options.counterparty);
230
+ const counterparties = parseSubjects(options.counterparty, 'counterparty');
220
231
  if (counterparties) data.counterparties = counterparties;
221
232
 
222
- const tokens = parseTokens(options.token);
223
- const excludeTokens = parseTokens(options['exclude-token']);
233
+ const tokens = parseTokens(options.token, 'token');
234
+ const excludeTokens = parseTokens(options['exclude-token'], 'exclude-token');
224
235
  if (tokens) data.inclusion = { ...data.inclusion, tokens };
225
236
  if (excludeTokens) data.exclusion = { ...data.exclusion, tokens: excludeTokens };
226
237
 
227
- const sectors = normArray(options['token-sector']);
238
+ const sectors = parseCsvOption(options['token-sector'], 'token-sector');
228
239
  if (sectors) data.inclusion = { ...data.inclusion, tokenSectors: sectors };
229
- const excludeSectors = normArray(options['exclude-token-sector']);
240
+ const excludeSectors = parseCsvOption(options['exclude-token-sector'], 'exclude-token-sector');
230
241
  if (excludeSectors) data.exclusion = { ...data.exclusion, tokenSectors: excludeSectors };
231
242
 
232
243
  const tokenAgeMin = options['token-age-min'];
@@ -241,9 +252,9 @@ export function buildCommonTokenTransferData(options) {
241
252
  const marketCapRange = buildRange(options['market-cap-min'], options['market-cap-max'], 'market-cap');
242
253
  if (marketCapRange) data.inclusion = { ...data.inclusion, marketCap: marketCapRange };
243
254
 
244
- const excludeFrom = parseSubjects(options['exclude-from']);
255
+ const excludeFrom = parseSubjects(options['exclude-from'], 'exclude-from');
245
256
  if (excludeFrom) data.exclusion = { ...data.exclusion, fromTargets: excludeFrom };
246
- const excludeTo = parseSubjects(options['exclude-to']);
257
+ const excludeTo = parseSubjects(options['exclude-to'], 'exclude-to');
247
258
  if (excludeTo) data.exclusion = { ...data.exclusion, toTargets: excludeTo };
248
259
 
249
260
  return data;
@@ -261,16 +272,13 @@ export function buildSmartContractCallData(options) {
261
272
  const usdRange = buildRange(options['usd-min'], options['usd-max'], 'usd');
262
273
  if (usdRange) data.usdValue = usdRange;
263
274
 
264
- if (options['signature-hash']) {
265
- data.signatureHash = Array.isArray(options['signature-hash'])
266
- ? options['signature-hash']
267
- : [options['signature-hash']];
268
- }
275
+ const signatureHash = parseCsvOption(options['signature-hash'], 'signature-hash');
276
+ if (signatureHash) data.signatureHash = signatureHash;
269
277
 
270
- const callers = parseSubjects(options.caller);
271
- const contracts = parseSubjects(options.contract);
272
- const excludeCallers = parseSubjects(options['exclude-caller']);
273
- const excludeContracts = parseSubjects(options['exclude-contract']);
278
+ const callers = parseSubjects(options.caller, 'caller');
279
+ const contracts = parseSubjects(options.contract, 'contract');
280
+ const excludeCallers = parseSubjects(options['exclude-caller'], 'exclude-caller');
281
+ const excludeContracts = parseSubjects(options['exclude-contract'], 'exclude-contract');
274
282
 
275
283
  if (callers) data.inclusion = { ...data.inclusion, caller: callers };
276
284
  if (contracts) data.inclusion = { ...data.inclusion, smartContract: contracts };
@@ -612,6 +620,8 @@ USAGE:
612
620
 
613
621
  const offset = parseNonNegativeIntegerOption(options.offset, 'offset');
614
622
  const limit = parseNonNegativeIntegerOption(options.limit, 'limit');
623
+ const tokenAddress = parseStringFilter(options['token-address'], 'token-address');
624
+ const chainFilter = parseStringFilter(options.chain, 'chain');
615
625
 
616
626
  const results = await apiInstance.alertsList();
617
627
  let alerts = Array.isArray(results) ? results : results?.alerts ?? results?.data ?? [];
@@ -620,15 +630,15 @@ USAGE:
620
630
  if (options.type) alerts = alerts.filter(a => a.type === options.type);
621
631
  if (flags.enabled) alerts = alerts.filter(a => a.isEnabled === true);
622
632
  if (flags.disabled) alerts = alerts.filter(a => a.isEnabled === false);
623
- if (options['token-address']) {
624
- const addr = options['token-address'].toLowerCase();
633
+ if (tokenAddress) {
634
+ const addr = tokenAddress.toLowerCase();
625
635
  alerts = alerts.filter(a => {
626
636
  const allTokens = [...(a.data?.inclusion?.tokens ?? []), ...(a.data?.exclusion?.tokens ?? [])];
627
637
  return allTokens.some(t => t.address?.toLowerCase() === addr);
628
638
  });
629
639
  }
630
- if (options.chain) {
631
- const ch = options.chain.toLowerCase();
640
+ if (chainFilter) {
641
+ const ch = chainFilter.toLowerCase();
632
642
  alerts = alerts.filter(a => {
633
643
  const chains = a.data?.chains;
634
644
  return Array.isArray(chains) && chains.some(c => c.toLowerCase() === ch || c === 'all');
@@ -246,6 +246,12 @@ export function buildMcpCommands(deps = {}) {
246
246
  if ('url' in options && typeof options.url !== 'string') {
247
247
  throw new CommandError('--url must be a single URL string. Usage: nansen mcp verify --url <url>', 'INVALID_PARAMS');
248
248
  }
249
+ // An explicit blank value, e.g. `--url "$UNSET_VAR"`, must not fall through
250
+ // to the default endpoint below: the caller would be told the Nansen URL
251
+ // verified while believing they had checked their own.
252
+ if (typeof options.url === 'string' && options.url.trim() === '') {
253
+ throw new CommandError('--url requires a value. Usage: nansen mcp verify --url <url>', 'MISSING_PARAM');
254
+ }
249
255
 
250
256
  const url = options.url || DEFAULT_MCP_URL;
251
257
  const checks = await runMcpVerifyChecks({
@@ -5,7 +5,7 @@
5
5
  */
6
6
 
7
7
  import { NansenError, ErrorCode } from '../api.js';
8
- import { parseSort } from '../query-options.js';
8
+ import { parseSort, rejectBlankOption } from '../query-options.js';
9
9
 
10
10
  // Research subcommands validate --page strictly. The shared helper in
11
11
  // src/query-options.js clamps an invalid page to 1 for the category commands,
@@ -68,7 +68,7 @@ function resolveDateRange(options) {
68
68
  }
69
69
 
70
70
  function parseTimeframeDays(value) {
71
- if (value === undefined || value === null || value === '') return undefined;
71
+ if (value === undefined || value === null) return undefined;
72
72
  const trimmed = String(value).trim();
73
73
  if (!/^[1-9]\d*$/.test(trimmed)) {
74
74
  throw new NansenError('--timeframe-days must be a positive integer', ErrorCode.INVALID_PARAMS);
@@ -245,6 +245,13 @@ export function buildResearchCommands(deps = {}) {
245
245
 
246
246
  if (sub === 'token-sectors') return apiInstance.tokenSectors();
247
247
 
248
+ for (const [name, example] of [
249
+ ['chain', 'solana'], ['chains', 'solana'], ['chain-type', 'all'],
250
+ ['timeframe', '1d'], ['timeframe-days', '7'],
251
+ ]) {
252
+ rejectBlankOption(options[name], name, example);
253
+ }
254
+
248
255
  const orderBy = parseSort(options.sort, options['order-by']);
249
256
  const pagination = buildPagination(options);
250
257
  const filters = options.filters || {};
package/src/cost-cache.js CHANGED
@@ -77,13 +77,21 @@ export async function refreshCostMapIfStale() {
77
77
  let spec;
78
78
  try {
79
79
  const res = await fetch(OPENAPI_URL, { signal: controller.signal });
80
+ // An error body still parses as JSON. Writing it would stamp fetchedAt
81
+ // fresh, replacing known-good costs with an empty map and suppressing the
82
+ // next attempt for STALE_MS.
83
+ if (!res.ok) return;
80
84
  spec = await res.json();
81
85
  } finally {
82
86
  clearTimeout(timer);
83
87
  }
84
88
 
89
+ // No paths object means this is not the spec. Treat it as a failed fetch
90
+ // rather than as "every endpoint is free".
91
+ if (!spec?.paths || typeof spec.paths !== 'object') return;
92
+
85
93
  const costs = {};
86
- for (const [p, methods] of Object.entries(spec.paths || {})) {
94
+ for (const [p, methods] of Object.entries(spec.paths)) {
87
95
  for (const op of Object.values(methods)) {
88
96
  if (op['x-credit-cost']) {
89
97
  costs[p] = op['x-credit-cost'];
@@ -6,6 +6,7 @@
6
6
  * Zero external dependencies — uses Node.js built-in crypto only.
7
7
  */
8
8
 
9
+ import { rejectBlankOption } from './query-options.js';
9
10
  import fs from 'fs';
10
11
  import path from 'path';
11
12
  import { base58Encode, exportWallet, getWalletConfig, showWallet } from './wallet.js';
@@ -624,6 +625,8 @@ export function buildLimitOrderCommands(deps = {}) {
624
625
 
625
626
  return {
626
627
  'create': async (args, apiInstance, flags, options) => {
628
+ rejectBlankOption(options.wallet, 'wallet', '<name>');
629
+ rejectBlankOption(options.expires, 'expires', '7d');
627
630
  const fromRaw = options.from || options['from-token'] || args[0];
628
631
  const toRaw = options.to || options['to-token'] || args[1];
629
632
  const from = resolveTokenAddress(fromRaw, 'solana');
@@ -885,6 +888,11 @@ EXAMPLES:
885
888
  },
886
889
 
887
890
  'list': async (args, apiInstance, flags, options) => {
891
+ rejectBlankOption(options.mint, 'mint', 'SOL');
892
+ rejectBlankOption(options.limit, 'limit', '20');
893
+ rejectBlankOption(options.offset, 'offset', '0');
894
+ rejectBlankOption(options.dir, 'dir', 'desc');
895
+ rejectBlankOption(options.wallet, 'wallet', '<name>');
888
896
  const walletName = options.wallet;
889
897
  const state = options.state;
890
898
  const mint = options.mint ? resolveTokenAddress(options.mint, 'solana') : undefined;
@@ -944,6 +952,7 @@ EXAMPLES:
944
952
  },
945
953
 
946
954
  'cancel': async (args, apiInstance, flags, options) => {
955
+ rejectBlankOption(options.wallet, 'wallet', '<name>');
947
956
  const orderId = options.order || options['order-id'] || args[0];
948
957
  const walletName = options.wallet;
949
958
 
@@ -1074,6 +1083,7 @@ EXAMPLES:
1074
1083
  },
1075
1084
 
1076
1085
  'update': async (args, apiInstance, flags, options) => {
1086
+ rejectBlankOption(options.wallet, 'wallet', '<name>');
1077
1087
  const orderId = options.order || options['order-id'] || args[0];
1078
1088
  const triggerPrice = options['trigger-price'];
1079
1089
  const slippageBps = options['slippage-bps'];
@@ -6,7 +6,7 @@
6
6
  * implementation without circular imports.
7
7
  */
8
8
 
9
- import { NansenError, ErrorCode } from './api.js';
9
+ import { NansenError, CommandError, ErrorCode } from './api.js';
10
10
 
11
11
  export function buildPagination(options) {
12
12
  if (options.limit === undefined && options.page === undefined) return undefined;
@@ -30,3 +30,32 @@ export function parseSort(sortOption, orderByOption) {
30
30
  const direction = (parts[1] || 'desc').toUpperCase();
31
31
  return [{ field, direction }];
32
32
  }
33
+
34
+ /**
35
+ * Normalise a comma-separated-string-or-array CLI option into an array of
36
+ * strings, or undefined if absent. Accepts either a single "a,b,c" string or
37
+ * an array (parseArgs collects repeated flags, e.g. `--tag a --tag b`, into
38
+ * one), and rejects non-string values/elements (e.g. `--flag true` is
39
+ * parsed by parseArgs as the JSON boolean `true`) with an actionable
40
+ * INVALID_PARAMS error instead of crashing on .split()/.trim().
41
+ */
42
+ export function parseCsvOption(val, name) {
43
+ if (val === undefined || val === '') return undefined;
44
+ if (Array.isArray(val)) {
45
+ if (!val.every(v => typeof v === 'string')) {
46
+ throw new NansenError(`--${name} values must be strings`, ErrorCode.INVALID_PARAMS);
47
+ }
48
+ return val.map(v => v.trim()).filter(Boolean);
49
+ }
50
+ if (typeof val !== 'string') {
51
+ throw new NansenError(`--${name} must be a string`, ErrorCode.INVALID_PARAMS);
52
+ }
53
+ return val.split(',').map(s => s.trim()).filter(Boolean);
54
+ }
55
+
56
+ /** Reject explicit blank strings before a handler selects an omitted-option default. */
57
+ export function rejectBlankOption(value, name, example) {
58
+ if (typeof value === 'string' && value.trim() === '') {
59
+ throw new CommandError(`--${name} requires a value. Usage: --${name} ${example}`, 'MISSING_PARAM');
60
+ }
61
+ }