nansen-cli 1.45.0 → 2.0.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.
Files changed (85) hide show
  1. package/CHANGELOG.md +172 -0
  2. package/README.md +158 -18
  3. package/docs/browser-login.md +117 -0
  4. package/package.json +11 -2
  5. package/scripts/postinstall.js +35 -30
  6. package/skills/nansen-agent-guide/SKILL.md +13 -2
  7. package/skills/nansen-alerts-webhook-listener/SKILL.md +5 -2
  8. package/skills/nansen-dca-tracker/SKILL.md +10 -2
  9. package/skills/nansen-defi-positions/SKILL.md +5 -2
  10. package/skills/nansen-exit-signals/SKILL.md +10 -2
  11. package/skills/nansen-fund-tracker/SKILL.md +10 -2
  12. package/skills/nansen-general-search/SKILL.md +10 -2
  13. package/skills/nansen-holder-analysis/SKILL.md +10 -2
  14. package/skills/nansen-limit-orders/SKILL.md +6 -3
  15. package/skills/nansen-perp-screener/SKILL.md +10 -2
  16. package/skills/nansen-perp-trader-profile/SKILL.md +10 -2
  17. package/skills/nansen-polymarket-deep-dive/SKILL.md +10 -2
  18. package/skills/nansen-polymarket-insider-scan/SKILL.md +10 -2
  19. package/skills/nansen-polymarket-trader-profile/SKILL.md +10 -2
  20. package/skills/nansen-portfolio-tracker/SKILL.md +10 -2
  21. package/skills/nansen-prediction-markets/SKILL.md +10 -2
  22. package/skills/nansen-sm-cross-chain-flows/SKILL.md +10 -2
  23. package/skills/nansen-smart-alerts/SKILL.md +9 -4
  24. package/skills/nansen-smart-money-alpha/SKILL.md +10 -2
  25. package/skills/nansen-smart-money-tracker/SKILL.md +10 -2
  26. package/skills/nansen-smart-money-trend/SKILL.md +10 -2
  27. package/skills/nansen-token-research/SKILL.md +10 -2
  28. package/skills/nansen-token-screener/SKILL.md +14 -4
  29. package/skills/nansen-token-transfer-analysis/SKILL.md +10 -2
  30. package/skills/nansen-trading/SKILL.md +27 -2
  31. package/skills/nansen-wallet-batch/SKILL.md +10 -2
  32. package/skills/nansen-wallet-clustering/SKILL.md +10 -2
  33. package/skills/nansen-wallet-deep-dive/SKILL.md +10 -2
  34. package/skills/nansen-wallet-keychain-migration/SKILL.md +23 -15
  35. package/skills/nansen-wallet-manager/SKILL.md +26 -10
  36. package/skills/nansen-wallet-profiler/SKILL.md +10 -2
  37. package/skills/nansen-web-fetcher/SKILL.md +5 -2
  38. package/skills/nansen-web-searcher/SKILL.md +5 -2
  39. package/src/api.js +319 -129
  40. package/src/auth-browser.js +16 -0
  41. package/src/auth-credentials.js +73 -0
  42. package/src/auth-device.js +242 -0
  43. package/src/auth-key-input.js +46 -0
  44. package/src/auth-login.js +90 -0
  45. package/src/auth-state.js +487 -0
  46. package/src/auth-store-native.js +20 -0
  47. package/src/auth-store-worker.js +64 -0
  48. package/src/auth-store.js +140 -0
  49. package/src/auto-paginate.js +272 -0
  50. package/src/bridge.js +309 -85
  51. package/src/cache-inspect.js +345 -0
  52. package/src/chain-ids.js +1 -2
  53. package/src/cli.js +779 -286
  54. package/src/commands/agent.js +20 -9
  55. package/src/commands/alerts.js +1 -1
  56. package/src/commands/completion.js +2 -15
  57. package/src/commands/mcp.js +22 -20
  58. package/src/commands/research.js +4 -2
  59. package/src/cost-cache.js +16 -2
  60. package/src/debug.js +348 -0
  61. package/src/doctor.js +22 -45
  62. package/src/ens.js +3 -1
  63. package/src/execute-guard.js +116 -0
  64. package/src/hl-action.js +41 -13
  65. package/src/limit-order.js +9 -1
  66. package/src/mcp-client-config.js +169 -0
  67. package/src/mcp-client-config.json +17 -0
  68. package/src/mcp-verify.js +6 -5
  69. package/src/perp.js +61 -9
  70. package/src/privy.js +12 -12
  71. package/src/query-options.js +38 -6
  72. package/src/response-meta.js +57 -2
  73. package/src/rpc-urls.js +9 -11
  74. package/src/schema.json +309 -30
  75. package/src/semver.js +23 -4
  76. package/src/swap-simulation.js +35 -30
  77. package/src/telemetry.js +20 -0
  78. package/src/trading.js +806 -40
  79. package/src/transfer.js +75 -9
  80. package/src/update-check.js +9 -1
  81. package/src/wallet.js +240 -20
  82. package/src/walletconnect-trading.js +29 -8
  83. package/src/walletconnect-x402.js +9 -5
  84. package/src/x402-svm.js +123 -64
  85. package/src/x402.js +46 -14
package/src/doctor.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { renewalStatus } from './auth-state.js';
2
+ import { authConfigView, authDirectory } from './auth-credentials.js';
1
3
  /**
2
4
  * Nansen CLI - Offline diagnostics
3
5
  *
@@ -86,46 +88,7 @@ const DEV_CONFIG_PATH = path.join(__dirname, '..', 'config.json');
86
88
  * overrides — but lazily and without secrets leaving this function unmasked.
87
89
  */
88
90
  export function resolveAuthConfig(env, devConfigPath = DEV_CONFIG_PATH) {
89
- const userConfigPath = getConfigFilePath(env);
90
-
91
- let config = null;
92
- let configPath = null;
93
- let configError = null;
94
-
95
- if (fs.existsSync(userConfigPath)) {
96
- const result = readJsonDetailed(userConfigPath);
97
- config = result.data;
98
- configPath = userConfigPath;
99
- configError = result.error;
100
- }
101
- if (!config && fs.existsSync(devConfigPath)) {
102
- config = readJson(devConfigPath);
103
- if (config) configPath = devConfigPath;
104
- }
105
-
106
- let apiKey = config?.apiKey || null;
107
- let apiKeySource = apiKey ? (configPath === devConfigPath ? 'dev-config' : 'config') : null;
108
- if (env.NANSEN_API_KEY) {
109
- apiKey = env.NANSEN_API_KEY;
110
- apiKeySource = 'env';
111
- }
112
-
113
- let baseUrl = config?.baseUrl || DEFAULT_BASE_URL;
114
- let baseUrlSource = config?.baseUrl ? 'config' : 'default';
115
- if (env.NANSEN_BASE_URL) {
116
- baseUrl = env.NANSEN_BASE_URL;
117
- baseUrlSource = 'env';
118
- }
119
-
120
- return {
121
- apiKey,
122
- apiKeySource,
123
- baseUrl,
124
- baseUrlSource,
125
- configPath,
126
- configFileExists: fs.existsSync(userConfigPath),
127
- configError,
128
- };
91
+ return authConfigView(env, devConfigPath);
129
92
  }
130
93
 
131
94
  /**
@@ -213,7 +176,16 @@ export function getAuthStatus(deps = {}) {
213
176
  const defaultEntry = walletInfo.wallets.find(w => w.name === walletInfo.defaultWallet) || null;
214
177
 
215
178
  return {
216
- logged_in: Boolean(auth.apiKey),
179
+ logged_in: Boolean(auth.apiKey || auth.selected.kind === 'session'),
180
+ effective_credential: { kind: auth.selected.kind, source: auth.selected.source, validity: 'unverified' },
181
+ saved_session: auth.config.auth?.active?.kind === 'session' ? {
182
+ account_id: auth.config.auth.active.accountId,
183
+ expires_at: auth.config.auth.active.expiresAt,
184
+ expired: auth.config.auth.active.expiresAt <= Date.now(),
185
+ validity: 'cached_unverified',
186
+ storage_access: 'not_checked_no_prompt',
187
+ renewal_state: renewalStatus(authDirectory(env), auth.config.auth),
188
+ } : null,
217
189
  api_key: {
218
190
  present: Boolean(auth.apiKey),
219
191
  source: auth.apiKeySource,
@@ -288,9 +260,9 @@ export function runDoctorChecks(deps = {}) {
288
260
  // Report the URL the CLI will actually use — a config file can set a
289
261
  // non-default base URL too, not just the env var
290
262
  if (auth.baseUrlSource === 'env') {
291
- checks.push(check('base-url', 'warn', `NANSEN_BASE_URL override active: ${auth.baseUrl}`, `Unset NANSEN_BASE_URL to use ${DEFAULT_BASE_URL}`));
263
+ checks.push(check('base-url', 'warn', `NANSEN_BASE_URL override active: ${auth.baseUrl}`, `Unset NANSEN_BASE_URL to use the saved baseUrl, or ${DEFAULT_BASE_URL} when none is saved`));
292
264
  } else if (auth.baseUrl !== DEFAULT_BASE_URL) {
293
- checks.push(check('base-url', 'warn', `Non-default API base URL in ${auth.configPath}: ${auth.baseUrl}`, 'Run: nansen login (re-saves the default)'));
265
+ checks.push(check('base-url', 'warn', `Non-default API base URL in ${auth.configPath}: ${auth.baseUrl}`, 'Correct baseUrl in config.json or set NANSEN_BASE_URL=https://api.nansen.ai for this invocation. Plain login preserves the selected origin.'));
294
266
  } else {
295
267
  checks.push(check('base-url', 'ok', `API base URL: ${auth.baseUrl}`));
296
268
  }
@@ -299,9 +271,14 @@ export function runDoctorChecks(deps = {}) {
299
271
  if (auth.configError === 'unreadable') {
300
272
  checks.push(check('config-file', 'error', `${getConfigFilePath(env)} exists but cannot be read — permission problem?`, `Check ownership and mode: ls -l "${getConfigFilePath(env)}"`));
301
273
  } else if (auth.configError === 'parse') {
302
- checks.push(check('config-file', 'error', `${getConfigFilePath(env)} exists but is not valid JSON`, 'Run: nansen login (re-saves the file)'));
274
+ checks.push(check('config-file', 'error', `${getConfigFilePath(env)} exists but is not valid JSON`, 'Restore or repair config.json before retrying nansen login'));
275
+ }
276
+ if (auth.configError === 'format') {
277
+ checks.push(check('config-file', 'error', `${getConfigFilePath(env)} has an unrecognized auth format`, 'Restore or repair config.json before retrying. Do not delete secure-store credentials to repair this file.'));
303
278
  }
304
- if (auth.apiKey) {
279
+ if (auth.selected.kind === 'session') {
280
+ checks.push(check('browser-session', 'warn', 'Saved browser session metadata is cached and unverified; secure storage was not opened.', 'Run: nansen account for a live check'));
281
+ } else if (auth.apiKey) {
305
282
  const sourceLabel = auth.apiKeySource === 'env'
306
283
  ? 'NANSEN_API_KEY env var'
307
284
  : `config file ${auth.configPath}`;
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
+ }
package/src/hl-action.js CHANGED
@@ -170,7 +170,23 @@ export function encodeMsgpack(v) {
170
170
  // precision, then strip trailing zeros (Decimal.normalize + `:f`). Produces the
171
171
  // canonical decimal string HL expects in order wires (e.g. 1924.7 -> "1924.7",
172
172
  // 0.006 -> "0.006", 2000 -> "2000"). No scientific notation.
173
- export function floatToWire(x) {
173
+ export function floatToWire(x, field = 'order value') {
174
+ // toFixed() switches to exponential notation from 1e21 up ("1e+21"), which
175
+ // is not a decimal string HL's parser accepts. The precision check below
176
+ // does not catch it (parseFloat("1e+21") === 1e21) and the trailing-zero
177
+ // strip is skipped for a string with no ".", so the malformed value would
178
+ // reach the signed action and be rejected opaquely after signing.
179
+ // buildUsdClassTransferAction refuses the same boundary for transfer
180
+ // amounts; order price/size and trigger prices go through here.
181
+ //
182
+ // Rounding happens before this call, so the reported value can differ from
183
+ // what the user typed: roundPrice(9.99999e20) lands on exactly 1e21.
184
+ if (!Number.isFinite(x) || Math.abs(x) >= 1e21) {
185
+ throw new CommandError(
186
+ `Invalid ${field}: ${x}. Must be a finite number below 1e21.`,
187
+ 'INVALID_INPUT',
188
+ );
189
+ }
174
190
  const rounded = x.toFixed(8);
175
191
  if (Math.abs(parseFloat(rounded) - x) >= 1e-12) {
176
192
  throw new Error(`floatToWire causes rounding: ${x}`);
@@ -240,14 +256,14 @@ export function roundPrice(price, szDecimals) {
240
256
 
241
257
  // ── Order wire assembly (ports of signing.py) ────────────────────────
242
258
 
243
- function orderTypeToWire(orderType) {
259
+ function orderTypeToWire(orderType, priceField = 'trigger price') {
244
260
  if ('limit' in orderType) return { limit: orderType.limit };
245
261
  if ('trigger' in orderType) {
246
262
  // Key order matches the SDK: isMarket, triggerPx, tpsl.
247
263
  return {
248
264
  trigger: {
249
265
  isMarket: orderType.trigger.isMarket,
250
- triggerPx: floatToWire(orderType.trigger.triggerPx),
266
+ triggerPx: floatToWire(orderType.trigger.triggerPx, priceField),
251
267
  tpsl: orderType.trigger.tpsl,
252
268
  },
253
269
  };
@@ -258,14 +274,16 @@ function orderTypeToWire(orderType) {
258
274
  // Port of `order_request_to_order_wire`. Key order (a,b,p,s,r,t) is load-bearing
259
275
  // — it's the msgpack map insertion order the hash depends on. No cloid ("c"):
260
276
  // the CLI never sets one.
261
- function orderRequestToOrderWire(order, asset) {
277
+ // priceField names the CLI flag this leg's price came from, so a rejected value
278
+ // points at --take-profit / --stop-loss rather than at a generic "order price".
279
+ function orderRequestToOrderWire(order, asset, priceField = 'order price') {
262
280
  return {
263
281
  a: asset,
264
282
  b: order.isBuy,
265
- p: floatToWire(order.limitPx),
266
- s: floatToWire(order.sz),
283
+ p: floatToWire(order.limitPx, priceField),
284
+ s: floatToWire(order.sz, 'order size'),
267
285
  r: order.reduceOnly,
268
- t: orderTypeToWire(order.orderType),
286
+ t: orderTypeToWire(order.orderType, priceField),
269
287
  };
270
288
  }
271
289
 
@@ -284,20 +302,27 @@ function orderWiresToOrderAction(orderWires, builder, grouping = 'na') {
284
302
  // limit computed below, to match the reference implementation. A take-profit set
285
303
  // just past the mark on a market order can therefore land inside the slippage
286
304
  // band; that is accepted here rather than rejected.
287
- function validateTpsl({ isBuy, price, takeProfit, stopLoss }) {
305
+ //
306
+ // Throws a coded CommandError like every other guard in this file and in
307
+ // perp.js, so an agent can branch on `code` instead of matching the message.
308
+ //
309
+ // Exported so perp.js can run it before resolving a signing context or
310
+ // submitting the builder-fee approval. buildOrderAction still calls it, so the
311
+ // guard stays attached to the build for any other caller.
312
+ export function validateTpsl({ isBuy, price, takeProfit, stopLoss }) {
288
313
  if (isBuy) {
289
314
  if (stopLoss != null && stopLoss >= price) {
290
- throw new Error(`Stop-loss for a long must be below the entry price (${price}). Got: ${stopLoss}`);
315
+ throw new CommandError(`Stop-loss for a long must be below the entry price (${price}). Got: ${stopLoss}`, 'INVALID_INPUT');
291
316
  }
292
317
  if (takeProfit != null && takeProfit <= price) {
293
- throw new Error(`Take-profit for a long must be above the entry price (${price}). Got: ${takeProfit}`);
318
+ throw new CommandError(`Take-profit for a long must be above the entry price (${price}). Got: ${takeProfit}`, 'INVALID_INPUT');
294
319
  }
295
320
  } else {
296
321
  if (stopLoss != null && stopLoss <= price) {
297
- throw new Error(`Stop-loss for a short must be above the entry price (${price}). Got: ${stopLoss}`);
322
+ throw new CommandError(`Stop-loss for a short must be above the entry price (${price}). Got: ${stopLoss}`, 'INVALID_INPUT');
298
323
  }
299
324
  if (takeProfit != null && takeProfit >= price) {
300
- throw new Error(`Take-profit for a short must be below the entry price (${price}). Got: ${takeProfit}`);
325
+ throw new CommandError(`Take-profit for a short must be below the entry price (${price}). Got: ${takeProfit}`, 'INVALID_INPUT');
301
326
  }
302
327
  }
303
328
  }
@@ -359,6 +384,7 @@ export function buildOrderAction(
359
384
  orderRequestToOrderWire(
360
385
  { isBuy: !isBuy, sz: roundedSize, limitPx: rtp, orderType: { trigger: { triggerPx: rtp, isMarket: true, tpsl: 'tp' } }, reduceOnly: true },
361
386
  assetId,
387
+ 'take-profit price',
362
388
  ),
363
389
  );
364
390
  }
@@ -371,6 +397,7 @@ export function buildOrderAction(
371
397
  orderRequestToOrderWire(
372
398
  { isBuy: !isBuy, sz: roundedSize, limitPx: rsl, orderType: { trigger: { triggerPx: rsl, isMarket: true, tpsl: 'sl' } }, reduceOnly: true },
373
399
  assetId,
400
+ 'stop-loss price',
374
401
  ),
375
402
  );
376
403
  }
@@ -508,8 +535,9 @@ export function buildUsdClassTransferAction({ amount, toPerp, nonce, network = h
508
535
  // rejection after signing. An amount that large is a mistake either way, so
509
536
  // refuse here.
510
537
  if (!Number.isFinite(amount) || amount <= 0 || amount >= 1e21) {
511
- throw new Error(
538
+ throw new CommandError(
512
539
  `Invalid usdClassTransfer amount: ${amount}. Must be a positive number below 1e21.`,
540
+ 'INVALID_INPUT',
513
541
  );
514
542
  }
515
543
  const strAmount = amount.toFixed(8).replace(/0+$/, '').replace(/\.$/, '');
@@ -711,7 +711,15 @@ EXAMPLES:
711
711
  const tokenInfo = await getTokenInfo(CHAIN_RPCS.solana, from);
712
712
  decimals = tokenInfo.decimals;
713
713
  }
714
- 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
+ }
715
723
  } catch (err) {
716
724
  log(`Error: Could not resolve decimals for ${from}: ${err.message}`);
717
725
  exit(1);
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Canonical MCP client install config (API-322).
3
+ *
4
+ * src/mcp-client-config.json is the one maintained source for the hosted MCP
5
+ * endpoint, the API-key header, the server-name key, the API-key URLs and the
6
+ * mcp-remote pin. This module loads and validates it, and builds the client
7
+ * config shapes from it. `nansen mcp install`, `nansen mcp verify`, the
8
+ * generated README regions (scripts/generate-mcp-docs.js), the public docs
9
+ * page and the nansen-mcp-dxt manifest all derive from the same file.
10
+ */
11
+
12
+ import fs from 'fs';
13
+
14
+ export const MCP_CLIENT_CONFIG_PATH = new URL('./mcp-client-config.json', import.meta.url);
15
+
16
+ // The only host that may receive the API key. This is a safety invariant, not
17
+ // a second copy of the endpoint: `install` writes the key into a config that
18
+ // sends it to `endpoint`, so a typo here must fail loudly at load time.
19
+ const MCP_HOST = 'mcp.nansen.ai';
20
+ const APP_HOST = 'app.nansen.ai';
21
+
22
+ const KNOWN_KEYS = [
23
+ '$comment',
24
+ 'schemaVersion',
25
+ 'serverKey',
26
+ 'endpoint',
27
+ 'oauthEndpoint',
28
+ 'apiKeyHeader',
29
+ 'apiKeyEnvVar',
30
+ 'apiKeySetupUrl',
31
+ 'apiKeyManageUrl',
32
+ 'docsUrl',
33
+ 'dxtDownloadUrl',
34
+ 'mcpRemote',
35
+ ];
36
+
37
+ function fail(message) {
38
+ throw new Error(`Invalid MCP client config: ${message}`);
39
+ }
40
+
41
+ function requireString(config, key) {
42
+ const value = config[key];
43
+ if (typeof value !== 'string' || value.trim() === '' || value !== value.trim()) {
44
+ fail(`"${key}" must be a non-empty string without surrounding whitespace`);
45
+ }
46
+ return value;
47
+ }
48
+
49
+ function requireHttpsUrl(config, key, { host, exactPath = false } = {}) {
50
+ const value = requireString(config, key);
51
+ let parsed;
52
+ try {
53
+ parsed = new URL(value);
54
+ } catch {
55
+ fail(`"${key}" is not a URL: ${value}`);
56
+ }
57
+ if (parsed.protocol !== 'https:') fail(`"${key}" must use https: ${value}`);
58
+ if (parsed.username || parsed.password) fail(`"${key}" must not contain credentials`);
59
+ // Docs paste these URLs into shell commands and markdown links.
60
+ if (/[\s'"`()<>$\\]/.test(value)) fail(`"${key}" contains a character that is unsafe in docs or shell: ${value}`);
61
+ if (parsed.hash) fail(`"${key}" must not contain a fragment: ${value}`);
62
+ if (host && parsed.hostname !== host) fail(`"${key}" must be on ${host}: ${value}`);
63
+ if (exactPath) {
64
+ // MCP endpoints: no query, no trailing slash, no port. The trailing-slash
65
+ // form was drift in the old .dxt manifest.
66
+ if (parsed.search) fail(`"${key}" must not contain a query: ${value}`);
67
+ if (parsed.port) fail(`"${key}" must not set a port: ${value}`);
68
+ if (parsed.pathname.endsWith('/')) fail(`"${key}" must not end with "/": ${value}`);
69
+ if (value !== `${parsed.origin}${parsed.pathname}`) fail(`"${key}" is not in canonical form: ${value}`);
70
+ if (!/^\/[A-Za-z0-9/_-]+$/.test(parsed.pathname)) fail(`"${key}" path must match ^/[A-Za-z0-9/_-]+$: ${value}`);
71
+ }
72
+ return value;
73
+ }
74
+
75
+ /**
76
+ * Validate a parsed config object. Returns it frozen, or throws an Error that
77
+ * names the bad field. Unknown keys fail too, so a misspelled key cannot be
78
+ * silently ignored by one consumer and read by another.
79
+ */
80
+ export function validateMcpClientConfig(config) {
81
+ if (typeof config !== 'object' || config === null || Array.isArray(config)) fail('must be a JSON object');
82
+ const unknown = Object.keys(config).filter(key => !KNOWN_KEYS.includes(key));
83
+ if (unknown.length) fail(`unknown key(s): ${unknown.join(', ')}`);
84
+ if (config.schemaVersion !== 1) fail('"schemaVersion" must be 1');
85
+
86
+ const serverKey = requireString(config, 'serverKey');
87
+ if (!/^[a-z][a-z0-9-]*$/.test(serverKey)) fail(`"serverKey" must match ^[a-z][a-z0-9-]*$: ${serverKey}`);
88
+ requireHttpsUrl(config, 'endpoint', { host: MCP_HOST, exactPath: true });
89
+ requireHttpsUrl(config, 'oauthEndpoint', { host: MCP_HOST, exactPath: true });
90
+ if (config.endpoint === config.oauthEndpoint) fail('"endpoint" and "oauthEndpoint" must differ');
91
+
92
+ const header = requireString(config, 'apiKeyHeader');
93
+ // mcp-remote parses --header values with /^([A-Za-z0-9_-]+):\s*(.*)$/.
94
+ if (!/^[A-Za-z0-9-]+$/.test(header)) fail(`"apiKeyHeader" must match ^[A-Za-z0-9-]+$: ${header}`);
95
+ const envVar = requireString(config, 'apiKeyEnvVar');
96
+ // NANSEN_ prefix: the key is written into the stdio `env` block under this
97
+ // name, so it must never shadow PATH, NODE_OPTIONS or similar.
98
+ if (!/^NANSEN_[A-Z0-9_]+$/.test(envVar)) fail(`"apiKeyEnvVar" must match ^NANSEN_[A-Z0-9_]+$: ${envVar}`);
99
+
100
+ requireHttpsUrl(config, 'apiKeySetupUrl', { host: APP_HOST });
101
+ requireHttpsUrl(config, 'apiKeyManageUrl', { host: APP_HOST });
102
+ requireHttpsUrl(config, 'docsUrl', { host: 'docs.nansen.ai' });
103
+ // Follows the dxt repo's main branch on purpose: the public docs link must
104
+ // serve the current reviewed build. Pin it to a release tag before any
105
+ // client downloads it without a person in the loop.
106
+ const dxt = requireHttpsUrl(config, 'dxtDownloadUrl', { host: 'github.com' });
107
+ if (!dxt.startsWith('https://github.com/nansen-ai/nansen-mcp-dxt/')) fail(`"dxtDownloadUrl" must be in nansen-ai/nansen-mcp-dxt: ${dxt}`);
108
+
109
+ const remote = config.mcpRemote;
110
+ if (typeof remote !== 'object' || remote === null || Array.isArray(remote)) fail('"mcpRemote" must be an object');
111
+ const remoteUnknown = Object.keys(remote).filter(key => key !== 'package' && key !== 'version');
112
+ if (remoteUnknown.length) fail(`unknown mcpRemote key(s): ${remoteUnknown.join(', ')}`);
113
+ if (remote.package !== 'mcp-remote') fail('"mcpRemote.package" must be "mcp-remote"');
114
+ // Exact version only: npx must never resolve a range or a dist-tag, because
115
+ // the bridge carries the API key on every request.
116
+ if (typeof remote.version !== 'string' || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(remote.version)) {
117
+ fail(`"mcpRemote.version" must be an exact x.y.z version: ${remote.version}`);
118
+ }
119
+
120
+ return Object.freeze({ ...config, mcpRemote: Object.freeze({ ...remote }) });
121
+ }
122
+
123
+ /** Load the packaged config file. The path is a constant: no caller input reaches readFileSync. */
124
+ export function loadMcpClientConfig() {
125
+ const raw = fs.readFileSync(MCP_CLIENT_CONFIG_PATH, 'utf8');
126
+ let parsed;
127
+ try {
128
+ parsed = JSON.parse(raw);
129
+ } catch (err) {
130
+ throw new Error(`Invalid MCP client config: ${err.message}`, { cause: err });
131
+ }
132
+ return validateMcpClientConfig(parsed);
133
+ }
134
+
135
+ export const MCP_CLIENT_CONFIG = loadMcpClientConfig();
136
+
137
+ /** `mcp-remote@x.y.z`, the exact spec passed to `npx -y`. */
138
+ export function mcpRemoteSpec(config = MCP_CLIENT_CONFIG) {
139
+ return `${config.mcpRemote.package}@${config.mcpRemote.version}`;
140
+ }
141
+
142
+ /**
143
+ * The single `--header` value for mcp-remote. `${VAR}` is not shell syntax:
144
+ * mcp-remote substitutes it from its own process env, so the key stays out of
145
+ * argv. See the comment in buildServerEntry (src/commands/mcp.js).
146
+ */
147
+ export function mcpRemoteHeaderArg(config = MCP_CLIENT_CONFIG) {
148
+ return `${config.apiKeyHeader}:\${${config.apiKeyEnvVar}}`;
149
+ }
150
+
151
+ /** Streamable-HTTP entry. `type: 'http'` is required by Claude Code, rejected by nothing else we write. */
152
+ export function buildHttpEntry(apiKey, { withType = false, config = MCP_CLIENT_CONFIG } = {}) {
153
+ const entry = withType ? { type: 'http' } : {};
154
+ return { ...entry, url: config.endpoint, headers: { [config.apiKeyHeader]: apiKey } };
155
+ }
156
+
157
+ /** stdio entry that bridges through the pinned mcp-remote via npx. */
158
+ export function buildStdioEntry(apiKey, { config = MCP_CLIENT_CONFIG } = {}) {
159
+ return {
160
+ command: 'npx',
161
+ args: ['-y', mcpRemoteSpec(config), config.endpoint, '--header', mcpRemoteHeaderArg(config)],
162
+ env: { [config.apiKeyEnvVar]: apiKey },
163
+ };
164
+ }
165
+
166
+ /** `claude mcp add` one-liner (placeholder only; never pass a real key into docs). */
167
+ export function buildClaudeCodeAddCommand(placeholder, { config = MCP_CLIENT_CONFIG } = {}) {
168
+ return `claude mcp add --transport http ${config.serverKey} ${config.endpoint} --header "${config.apiKeyHeader}: ${placeholder}"`;
169
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "$comment": "Canonical Nansen MCP client install config (API-322). Edit only this file, then run `npm run mcp:generate`. Consumers: src/commands/mcp.js, src/mcp-verify.js, README.md (generated regions), the docs page https://docs.nansen.ai/mcp/connecting and nansen-ai/nansen-mcp-dxt manifest.json (vendored copies pinned to a commit of this file). See AGENTS.md > MCP client config.",
3
+ "schemaVersion": 1,
4
+ "serverKey": "nansen",
5
+ "endpoint": "https://mcp.nansen.ai/ra/mcp",
6
+ "oauthEndpoint": "https://mcp.nansen.ai/ra/connector-curated/mcp",
7
+ "apiKeyHeader": "NANSEN-API-KEY",
8
+ "apiKeyEnvVar": "NANSEN_API_KEY",
9
+ "apiKeySetupUrl": "https://app.nansen.ai/auth/agent-setup",
10
+ "apiKeyManageUrl": "https://app.nansen.ai/api?tab=api",
11
+ "docsUrl": "https://docs.nansen.ai/mcp/connecting",
12
+ "dxtDownloadUrl": "https://github.com/nansen-ai/nansen-mcp-dxt/raw/refs/heads/main/nansen.dxt",
13
+ "mcpRemote": {
14
+ "package": "mcp-remote",
15
+ "version": "0.2.1"
16
+ }
17
+ }
package/src/mcp-verify.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { check, formatChecks, maskKey, resolveAuthConfig } from './doctor.js';
2
+ import { MCP_CLIENT_CONFIG } from './mcp-client-config.js';
2
3
 
3
- export const DEFAULT_MCP_URL = 'https://mcp.nansen.ai/ra/mcp';
4
+ export const DEFAULT_MCP_URL = MCP_CLIENT_CONFIG.endpoint;
4
5
  export const CANARY_TOOL = 'nansen_score_top_tokens';
5
6
 
6
7
  class McpRequestError extends Error {
@@ -98,7 +99,7 @@ export async function mcpRequest(url, method, params, {
98
99
  'Content-Type': 'application/json',
99
100
  Accept: 'application/json, text/event-stream',
100
101
  };
101
- if (apiKey) headers['NANSEN-API-KEY'] = apiKey;
102
+ if (apiKey) headers[MCP_CLIENT_CONFIG.apiKeyHeader] = apiKey;
102
103
 
103
104
  const timer = setTimeout(() => controller.abort(), timeoutMs);
104
105
  let response;
@@ -179,7 +180,7 @@ function authFailureCheck(message, httpStatus = null) {
179
180
  'mcp-auth',
180
181
  'error',
181
182
  `MCP server rejected the API key${text ? `: ${text}` : ''}`,
182
- 'Check the exact key in your MCP client\'s NANSEN-API-KEY header, or create/rotate it at https://app.nansen.ai/api?tab=api',
183
+ `Check the exact key in your MCP client's ${MCP_CLIENT_CONFIG.apiKeyHeader} header, or create/rotate it at ${MCP_CLIENT_CONFIG.apiKeyManageUrl}`,
183
184
  );
184
185
  }
185
186
  return check(
@@ -233,7 +234,7 @@ export async function runMcpVerifyChecks({
233
234
  'mcp-api-key',
234
235
  'error',
235
236
  'No API key available for the authenticated MCP data-path check',
236
- 'Create an API key at https://app.nansen.ai/api?tab=api, then set NANSEN_API_KEY or save it with `nansen login --human`',
237
+ `Create an API key at ${MCP_CLIENT_CONFIG.apiKeyManageUrl}, then set NANSEN_API_KEY or save it with \`nansen login --human\``,
237
238
  ));
238
239
  }
239
240
 
@@ -347,7 +348,7 @@ export async function runMcpVerifyChecks({
347
348
  export function formatMcpVerifyReport(checks, url, verified) {
348
349
  const lines = [`Nansen MCP verify — ${url}`, '', formatChecks(checks), ''];
349
350
  if (verified) {
350
- lines.push('Verified: the supplied API key works against the MCP server\'s paid data path (~1 credit consumed). Ensure this same key is in your client\'s NANSEN-API-KEY header.');
351
+ lines.push(`Verified: the supplied API key works against the MCP server's paid data path (~1 credit consumed). Ensure this same key is in your client's ${MCP_CLIENT_CONFIG.apiKeyHeader} header.`);
351
352
  } else {
352
353
  const errors = checks.filter(item => item.status === 'error').length;
353
354
  const warnings = checks.filter(item => item.status === 'warn').length;