nansen-cli 1.44.3 → 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.
@@ -74,8 +74,11 @@ export async function consumeSSEStream(response, callbacks = {}) {
74
74
 
75
75
  const processFrame = (frame) => {
76
76
  for (const line of frame.split('\n')) {
77
- if (!line.startsWith('data: ')) continue;
78
- const payload = line.slice(6);
77
+ if (!line.startsWith('data:')) continue;
78
+ // SSE permits `data:value` and `data: value`; discard at most the one
79
+ // optional space after the colon before parsing the field value.
80
+ const fieldValue = line.slice(5);
81
+ const payload = fieldValue.startsWith(' ') ? fieldValue.slice(1) : fieldValue;
79
82
  if (payload === '[DONE]') { done = true; return; }
80
83
 
81
84
  let event;
@@ -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 '{}'`, 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');
@@ -233,8 +233,8 @@ export function buildMcpCommands(deps = {}) {
233
233
  if (flags['api-key']) {
234
234
  throw new CommandError('--api-key requires a value. Usage: nansen mcp verify --api-key <key>', 'MISSING_PARAM');
235
235
  }
236
- // parseArgs JSON-parses option values, so `--api-key null` arrives as
237
- // null and a repeated flag as an array - both must fail, not fall back.
236
+ // parseArgs turns a repeated flag into an array and a JSON object/array
237
+ // value into an object - both must fail, not fall back.
238
238
  if ('api-key' in options && typeof options['api-key'] !== 'string') {
239
239
  throw new CommandError('--api-key must be a single key string. Usage: nansen mcp verify --api-key <key>', 'INVALID_PARAMS');
240
240
  }
@@ -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, parseObjectOption } 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);
@@ -79,6 +79,8 @@ function parseTimeframeDays(value) {
79
79
  function parseBooleanOption(options, flags, key) {
80
80
  const value = options[key] ?? flags[key];
81
81
  if (value === undefined) return undefined;
82
+ // Bare flags arrive through `flags` as true; explicit values arrive through
83
+ // `options` as strings (for example, `--apply-blacklist-filter false`).
82
84
  if (typeof value === 'boolean') return value;
83
85
  if (value === 'true' || value === '1') return true;
84
86
  if (value === 'false' || value === '0') return false;
@@ -245,9 +247,16 @@ export function buildResearchCommands(deps = {}) {
245
247
 
246
248
  if (sub === 'token-sectors') return apiInstance.tokenSectors();
247
249
 
250
+ for (const [name, example] of [
251
+ ['chain', 'solana'], ['chains', 'solana'], ['chain-type', 'all'],
252
+ ['timeframe', '1d'], ['timeframe-days', '7'],
253
+ ]) {
254
+ rejectBlankOption(options[name], name, example);
255
+ }
256
+
248
257
  const orderBy = parseSort(options.sort, options['order-by']);
249
258
  const pagination = buildPagination(options);
250
- const filters = options.filters || {};
259
+ const filters = parseObjectOption(options.filters, 'filters');
251
260
  const { fromDate, toDate } = resolveDateRange(options);
252
261
  const asOfDate = options['as-of-date'];
253
262
 
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'];
package/src/ens.js CHANGED
@@ -35,7 +35,9 @@ export async function resolveAddress(addressOrName, chain = 'ethereum') {
35
35
  return { address: trimmed };
36
36
  }
37
37
 
38
- if (!EVM_CHAINS.includes(chain)) {
38
+ // 'all' lets the API route by address format; a resolved .eth name is an
39
+ // EVM address, so it resolves the same way an explicit EVM chain does.
40
+ if (chain !== 'all' && !EVM_CHAINS.includes(chain)) {
39
41
  throw new Error(`ENS names can only be resolved on EVM chains, not ${chain}`);
40
42
  }
41
43
 
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Acknowledgement gate shared by the commands that move funds on-chain
3
+ * (`trade execute`, `bridge execute`).
4
+ *
5
+ * Two independent switches, both resolved in the command layer:
6
+ * --dry-run run the validation the command normally runs, print the plan,
7
+ * and stop before anything is signed or broadcast (exit 0).
8
+ * --yes / -y skip the confirmation. `NANSEN_YES=1` is the environment
9
+ * equivalent, for callers that cannot add a flag.
10
+ *
11
+ * The confirmation is only ever shown when stdin is an interactive terminal.
12
+ * Agents, CI jobs and pipes (stdin not a TTY) keep today's behaviour exactly:
13
+ * the command proceeds without asking, so no automated workflow can hang on a
14
+ * question nobody is there to answer. `--yes` is still accepted there and is
15
+ * simply a no-op. Declining the prompt exits 1 with nothing signed.
16
+ */
17
+
18
+ import { CommandError } from './api.js';
19
+
20
+ // Accepted spellings for NANSEN_YES. Anything else (unset, "0", "false", an
21
+ // empty string) leaves the confirmation in place.
22
+ const TRUTHY_ENV_VALUES = new Set(['1', 'true', 'yes', 'on']);
23
+
24
+ export function isYesEnvSet(env = process.env) {
25
+ const raw = env?.NANSEN_YES;
26
+ return typeof raw === 'string' && TRUTHY_ENV_VALUES.has(raw.trim().toLowerCase());
27
+ }
28
+
29
+ /**
30
+ * Read the guard's inputs off the parsed flags. `-y` arrives as `flags.y`
31
+ * because single-dash tokens are always parsed as valueless flags.
32
+ */
33
+ export function resolveExecuteGuard(flags = {}, { env = process.env, isTTY = false } = {}) {
34
+ return {
35
+ dryRun: Boolean(flags['dry-run']),
36
+ assumeYes: Boolean(flags.yes || flags.y) || isYesEnvSet(env),
37
+ isTTY: Boolean(isTTY),
38
+ };
39
+ }
40
+
41
+ /**
42
+ * Render `[label, value]` pairs as an aligned block. Pairs whose value is
43
+ * null/undefined/'' are dropped, so callers can list optional fields inline.
44
+ */
45
+ export function formatPlan(title, rows = [], notes = []) {
46
+ const shown = rows.filter(([, value]) => value !== undefined && value !== null && value !== '');
47
+ const width = shown.reduce((max, [label]) => Math.max(max, label.length + 1), 0);
48
+ return [
49
+ `\n ${title}`,
50
+ ...shown.map(([label, value]) => ` ${`${label}:`.padEnd(width)} ${value}`),
51
+ ...notes.map(note => ` ${note}`),
52
+ ].join('\n');
53
+ }
54
+
55
+ function isAffirmative(answer) {
56
+ return /^y(es)?$/i.test(String(answer ?? '').trim());
57
+ }
58
+
59
+ /**
60
+ * Print the plan and decide whether the caller may proceed to sign/broadcast.
61
+ *
62
+ * Returns true to continue, false when a dry run has finished (the caller
63
+ * returns without signing). Throws CONFIRMATION_DECLINED when an interactive
64
+ * user answers anything but yes.
65
+ */
66
+ export async function guardExecution({
67
+ plan,
68
+ dryRun = false,
69
+ assumeYes = false,
70
+ isTTY = false,
71
+ promptFn,
72
+ log = () => {},
73
+ confirmationLog = log,
74
+ question = 'Broadcast this transaction? [y/N] ',
75
+ }) {
76
+ if (dryRun) {
77
+ log(plan);
78
+ log('\n DRY RUN — nothing was broadcast. No transaction was signed and the quote was not consumed.');
79
+ log(' Re-run without --dry-run to sign and broadcast it.\n');
80
+ return false;
81
+ }
82
+
83
+ // Non-interactive stdin (agents, CI, pipes): unchanged, deterministic, never
84
+ // blocked on a prompt. --yes is accepted here and does nothing.
85
+ if (!isTTY || assumeYes) return true;
86
+
87
+ if (typeof promptFn !== 'function') {
88
+ throw new CommandError(
89
+ 'Cannot request confirmation because no interactive prompt is available. Pass --yes to proceed or --dry-run to preview.',
90
+ 'CONFIRMATION_UNAVAILABLE',
91
+ );
92
+ }
93
+
94
+ // Keep the plan on the same visible terminal channel as the question. In
95
+ // particular, stdin can still be a TTY when stdout is redirected to a file;
96
+ // writing the plan through `log` there would ask the user to approve a plan
97
+ // they cannot see. Dry-run output deliberately remains on `log`/stdout above
98
+ // because it is automation-friendly command output rather than a prompt.
99
+ confirmationLog(plan);
100
+ const answer = await promptFn(question);
101
+ if (!isAffirmative(answer)) {
102
+ const error = new CommandError(
103
+ 'Aborted at the confirmation prompt — nothing was signed or broadcast. '
104
+ + 'Pass --yes (or set NANSEN_YES=1) to skip this confirmation, or --dry-run to preview without broadcasting.',
105
+ 'CONFIRMATION_DECLINED',
106
+ );
107
+ // The interactive user is looking at the same terminal channel as the
108
+ // prompt, so report the decline there exactly once. runCLI sees `reported`
109
+ // and does not also serialize an agent-oriented JSON envelope to stdout.
110
+ // Direct callers still receive the complete CommandError below.
111
+ confirmationLog(error.message);
112
+ error.reported = true;
113
+ throw error;
114
+ }
115
+ return true;
116
+ }
@@ -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');
@@ -708,7 +711,15 @@ EXAMPLES:
708
711
  const tokenInfo = await getTokenInfo(CHAIN_RPCS.solana, from);
709
712
  decimals = tokenInfo.decimals;
710
713
  }
711
- amountBaseUnits = String(parseAmount(String(amount), decimals));
714
+ try {
715
+ amountBaseUnits = String(parseAmount(String(amount), decimals));
716
+ } catch (err) {
717
+ // parseAmount rejects an amount that truncates to zero base units at
718
+ // this token's precision — a decimals problem only in name.
719
+ log(`Error: ${err.message}`);
720
+ exit(1);
721
+ return;
722
+ }
712
723
  } catch (err) {
713
724
  log(`Error: Could not resolve decimals for ${from}: ${err.message}`);
714
725
  exit(1);
@@ -885,6 +896,11 @@ EXAMPLES:
885
896
  },
886
897
 
887
898
  'list': async (args, apiInstance, flags, options) => {
899
+ rejectBlankOption(options.mint, 'mint', 'SOL');
900
+ rejectBlankOption(options.limit, 'limit', '20');
901
+ rejectBlankOption(options.offset, 'offset', '0');
902
+ rejectBlankOption(options.dir, 'dir', 'desc');
903
+ rejectBlankOption(options.wallet, 'wallet', '<name>');
888
904
  const walletName = options.wallet;
889
905
  const state = options.state;
890
906
  const mint = options.mint ? resolveTokenAddress(options.mint, 'solana') : undefined;
@@ -944,6 +960,7 @@ EXAMPLES:
944
960
  },
945
961
 
946
962
  'cancel': async (args, apiInstance, flags, options) => {
963
+ rejectBlankOption(options.wallet, 'wallet', '<name>');
947
964
  const orderId = options.order || options['order-id'] || args[0];
948
965
  const walletName = options.wallet;
949
966
 
@@ -1074,6 +1091,7 @@ EXAMPLES:
1074
1091
  },
1075
1092
 
1076
1093
  'update': async (args, apiInstance, flags, options) => {
1094
+ rejectBlankOption(options.wallet, 'wallet', '<name>');
1077
1095
  const orderId = options.order || options['order-id'] || args[0];
1078
1096
  const triggerPrice = options['trigger-price'];
1079
1097
  const slippageBps = options['slippage-bps'];
package/src/perp.js CHANGED
@@ -175,10 +175,8 @@ function resolveWalletAddress(walletName) {
175
175
  // response that doesn't cover every requested address all abort the trade
176
176
  // before signing, never trade through.
177
177
 
178
- // Exported for bridge.js, which needs the same fail-closed check before it signs
179
- // (its EVM deposit leg broadcasts straight to a public RPC, so no server-side
180
- // screen sits in that path). Worth lifting into its own module if a third caller
181
- // appears.
178
+ // Shared with bridge.js and trading.js, whose direct signing/broadcast paths do
179
+ // not have a server-side screen after this checkpoint.
182
180
  export async function screenOrThrow(apiInstance, addresses) {
183
181
  let result;
184
182
  try {
@@ -196,7 +194,9 @@ export async function screenOrThrow(apiInstance, addresses) {
196
194
  }
197
195
 
198
196
  const results = Array.isArray(result?.results) ? result.results : [];
199
- const sanctioned = results.filter(r => r && r.sanctioned).map(r => r.address);
197
+ const sanctioned = results
198
+ .filter(r => r && r.sanctioned === true)
199
+ .map(r => r.address);
200
200
  if (sanctioned.length > 0) {
201
201
  throw new CommandError(
202
202
  `Wallet address is on the compliance blocklist and cannot trade: ${sanctioned.join(', ')}`,
@@ -204,10 +204,21 @@ export async function screenOrThrow(apiInstance, addresses) {
204
204
  );
205
205
  }
206
206
 
207
- // A 200 that omitted a requested address is unverifiable — fail closed rather
208
- // than assume the missing address is clean.
209
- const screened = new Set(results.map(r => String(r.address).toLowerCase()));
210
- const missing = addresses.filter(a => !screened.has(String(a).toLowerCase()));
207
+ // A 200 that omitted a requested address or did not return a boolean verdict
208
+ // is unverifiable — fail closed rather than assume the address is clean.
209
+ // EVM addresses are case-insensitive; base58 addresses (including Solana)
210
+ // are case-sensitive and must match exactly. Lowercasing every result here
211
+ // would let a verdict for a different Solana address satisfy the gate.
212
+ const addressKey = (address) => {
213
+ const value = String(address);
214
+ return /^0x[0-9a-f]{40}$/i.test(value) ? value.toLowerCase() : value;
215
+ };
216
+ const screened = new Set(
217
+ results
218
+ .filter(r => r && typeof r.sanctioned === 'boolean' && r.address != null)
219
+ .map(r => addressKey(r.address)),
220
+ );
221
+ const missing = addresses.filter(a => !screened.has(addressKey(a)));
211
222
  if (missing.length > 0) {
212
223
  throw new CommandError(
213
224
  `Compliance screening did not cover all addresses, so the trade was not submitted: ${missing.join(', ')}`,
@@ -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;
@@ -25,8 +25,69 @@ export function parseSort(sortOption, orderByOption) {
25
25
  // If --order-by is provided, use it (full JSON control)
26
26
  if (orderByOption) return orderByOption;
27
27
  if (!sortOption) return undefined;
28
- const parts = String(sortOption).split(':');
29
- const field = parts[0];
30
- const direction = (parts[1] || 'desc').toUpperCase();
28
+ if (typeof sortOption !== 'string') {
29
+ throw new NansenError('--sort must be "field" or "field:direction"', ErrorCode.INVALID_PARAMS);
30
+ }
31
+ const parts = sortOption.split(':');
32
+ const field = parts[0].trim();
33
+ const rawDirection = (parts[1] || '').trim();
34
+ const direction = (rawDirection || 'desc').toUpperCase();
35
+ if (!field) {
36
+ throw new NansenError('--sort needs a field name, e.g. --sort value_usd:desc', ErrorCode.INVALID_PARAMS);
37
+ }
38
+ if (direction !== 'ASC' && direction !== 'DESC') {
39
+ throw new NansenError(
40
+ `--sort direction must be asc or desc, got "${rawDirection}" (e.g. --sort ${field}:desc)`,
41
+ ErrorCode.INVALID_PARAMS,
42
+ );
43
+ }
31
44
  return [{ field, direction }];
32
45
  }
46
+
47
+ /**
48
+ * Normalise a comma-separated-string-or-array CLI option into an array of
49
+ * strings, or undefined if absent. Accepts either a single "a,b,c" string or
50
+ * an array (parseArgs collects repeated flags, e.g. `--tag a --tag b`, into
51
+ * one), and rejects non-string values/elements (e.g. `--flag '{}'` is
52
+ * parsed by parseArgs as a JSON object) with an actionable
53
+ * INVALID_PARAMS error instead of crashing on .split()/.trim().
54
+ */
55
+ export function parseCsvOption(val, name) {
56
+ if (val === undefined || val === '') return undefined;
57
+ if (Array.isArray(val)) {
58
+ if (!val.every(v => typeof v === 'string')) {
59
+ throw new NansenError(`--${name} values must be strings`, ErrorCode.INVALID_PARAMS);
60
+ }
61
+ // A repeated flag may itself carry a list (`--tags defi,nft --tags sports`),
62
+ // so split each element the same way a single value is split.
63
+ return val.flatMap(v => v.split(',')).map(v => v.trim()).filter(Boolean);
64
+ }
65
+ if (typeof val !== 'string') {
66
+ throw new NansenError(`--${name} must be a string`, ErrorCode.INVALID_PARAMS);
67
+ }
68
+ return val.split(',').map(s => s.trim()).filter(Boolean);
69
+ }
70
+
71
+ /**
72
+ * Normalise a `--filters '<json>'` option into a plain object, or `{}` when
73
+ * absent. parseArgs already JSON-parses the value, so anything that is not a
74
+ * plain object here (`--filters '[]'`, `--filters abc`, a repeated flag) would
75
+ * otherwise go straight into the request body and fail upstream with a 422.
76
+ */
77
+ export function parseObjectOption(val, name) {
78
+ if (val === undefined || val === '') return {};
79
+ if (val === null || typeof val !== 'object' || Array.isArray(val)) {
80
+ throw new NansenError(
81
+ `--${name} must be a JSON object, e.g. --${name} '{"key": "value"}'`,
82
+ ErrorCode.INVALID_PARAMS,
83
+ );
84
+ }
85
+ return val;
86
+ }
87
+
88
+ /** Reject explicit blank strings before a handler selects an omitted-option default. */
89
+ export function rejectBlankOption(value, name, example) {
90
+ if (typeof value === 'string' && value.trim() === '') {
91
+ throw new CommandError(`--${name} requires a value. Usage: --${name} ${example}`, 'MISSING_PARAM');
92
+ }
93
+ }
@@ -43,7 +43,7 @@ function intHeader(response, name) {
43
43
  * Read a header as a trimmed non-empty string, or null when absent.
44
44
  * Tolerates any header bag with a .get() — a real Headers, or a Map in tests.
45
45
  */
46
- function stringHeader(response, name) {
46
+ export function stringHeader(response, name) {
47
47
  const raw = response?.headers?.get?.(name);
48
48
  if (raw == null) return null;
49
49
  const value = String(raw).trim();