nansen-cli 1.46.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +157 -14
  3. package/docs/browser-login.md +123 -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 +8 -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 +5 -2
  35. package/skills/nansen-wallet-manager/SKILL.md +11 -9
  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 +202 -104
  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 +89 -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 +288 -0
  50. package/src/bridge.js +126 -21
  51. package/src/cache-inspect.js +345 -0
  52. package/src/cli.js +473 -199
  53. package/src/commands/agent.js +15 -7
  54. package/src/commands/completion.js +2 -15
  55. package/src/commands/mcp.js +20 -18
  56. package/src/cost-cache.js +16 -2
  57. package/src/debug.js +348 -0
  58. package/src/doctor.js +22 -45
  59. package/src/hl-action.js +41 -13
  60. package/src/limit-order.js +1 -1
  61. package/src/mcp-client-config.js +169 -0
  62. package/src/mcp-client-config.json +17 -0
  63. package/src/mcp-verify.js +6 -5
  64. package/src/perp.js +41 -0
  65. package/src/privy.js +12 -12
  66. package/src/response-meta.js +56 -1
  67. package/src/rpc-urls.js +9 -11
  68. package/src/schema.json +185 -8
  69. package/src/semver.js +23 -4
  70. package/src/swap-simulation.js +35 -30
  71. package/src/telemetry.js +20 -0
  72. package/src/trading.js +266 -29
  73. package/src/transfer.js +53 -6
  74. package/src/update-check.js +9 -1
  75. package/src/wallet.js +107 -17
  76. package/src/walletconnect-trading.js +24 -5
  77. package/src/x402-svm.js +123 -64
  78. 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/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(/\.$/, '');
@@ -111,7 +111,7 @@ async function loFetch(method, endpoint, { token, body, query } = {}) {
111
111
  if (token) {
112
112
  headers['Authorization'] = `Bearer ${token}`;
113
113
  }
114
- if (process.env.NANSEN_API_KEY) {
114
+ if (process.env.NANSEN_API_KEY?.trim()) {
115
115
  headers['X-API-Key'] = process.env.NANSEN_API_KEY;
116
116
  }
117
117
 
@@ -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;
package/src/perp.js CHANGED
@@ -20,8 +20,10 @@ import {
20
20
  buildUsdClassTransferAction,
21
21
  l1Eip712,
22
22
  userSignedEip712,
23
+ validateTpsl,
23
24
  } from './hl-action.js';
24
25
  import { submitExchange } from './hl-client.js';
26
+ import { hlApiUrl, hlNetwork } from './hl-env.js';
25
27
  import { trackPerpOrderCompleted } from './telemetry.js';
26
28
  import { resolveEvmWallet, resolvePrivateKey } from './wallet-signing.js';
27
29
  import { hashTypedData } from './x402-evm.js';
@@ -47,7 +49,31 @@ function signAgent(eip712, privateKeyHex) {
47
49
  // account) or feeds a signing decision (close sizes its order from positions,
48
50
  // and asset ids/szDecimals come from meta), so a hit inside the 5-minute TTL
49
51
  // would sign against data that has moved.
52
+ // Every read below comes from the Nansen proxy, which serves Hyperliquid
53
+ // MAINNET data — asset ids, szDecimals, positions, open orders, balances.
54
+ // Signing and submission, in contrast, follow NANSEN_HL_API_URL: hlNetwork()
55
+ // flips the L1 phantom-agent source and hyperliquidChain to Testnet and
56
+ // hl-client posts to the testnet host. Pointing the CLI at the testnet
57
+ // therefore signs mainnet asset indices into testnet orders (the two
58
+ // universes are not guaranteed to share an ordering), shows mainnet positions
59
+ // for a testnet account, and validates `close --side` against the wrong
60
+ // network's position. Refuse rather than mix the two, the way bridge.js
61
+ // refuses an action whose hyperliquidChain is not the network it targets.
62
+ //
63
+ // hlNetwork() only reports Testnet for a hyperliquid-testnet host, so a local
64
+ // mock (the other documented use of NANSEN_HL_API_URL) is unaffected.
65
+ function assertPerpNetworkSupported() {
66
+ const network = hlNetwork();
67
+ if (network !== 'Mainnet') {
68
+ throw new CommandError(
69
+ `Perp commands are mainnet-only: NANSEN_HL_API_URL points at ${hlApiUrl()} (${network}), but asset metadata, positions and balances come from the Nansen proxy, which serves mainnet data. Signing ${network} actions against mainnet asset ids could target a different instrument. Unset NANSEN_HL_API_URL to trade on mainnet.`,
70
+ 'UNSUPPORTED_NETWORK',
71
+ );
72
+ }
73
+ }
74
+
50
75
  async function perpRead(apiInstance, endpoint, params) {
76
+ assertPerpNetworkSupported();
51
77
  const qs = new URLSearchParams(params).toString();
52
78
  // Only append the query string when there is one; a paramless read like `meta`
53
79
  // would otherwise resolve to `/api/v1/perp/meta?` with a bare trailing `?`.
@@ -60,6 +86,9 @@ async function perpRead(apiInstance, endpoint, params) {
60
86
  // (missing wallet, wrong password) — callers that need it to build an action
61
87
  // re-check for null and abort at that point (see requireAsset).
62
88
  async function fetchAssetMeta(apiInstance, coin) {
89
+ // Before the try: a network mismatch is a configuration error the caller
90
+ // must see, not an availability problem to fail open on.
91
+ assertPerpNetworkSupported();
63
92
  try {
64
93
  const meta = await perpRead(apiInstance, 'meta', {});
65
94
  const asset = (meta.assets || []).find(a => String(a.name).toUpperCase() === coin);
@@ -107,6 +136,7 @@ const MAX_BUILDER_FEE_TENTHS_BP = 80;
107
136
  // gate. Fail closed — this endpoint shares availability with screening, so if
108
137
  // it's down we abort rather than trade without the builder code.
109
138
  async function fetchBuilderFee(apiInstance, walletAddress) {
139
+ assertPerpNetworkSupported();
110
140
  const qs = new URLSearchParams({ wallet_address: walletAddress }).toString();
111
141
  let status;
112
142
  try {
@@ -346,6 +376,10 @@ async function buildScreenSignSubmit(apiInstance, prepared, ctx) {
346
376
  const { action, nonce, eip712, size, price, coin, telemetry } = prepared;
347
377
  const { walletAddress, log } = ctx;
348
378
 
379
+ // Last gate before a signature: every action built above used proxy-sourced
380
+ // mainnet metadata.
381
+ assertPerpNetworkSupported();
382
+
349
383
  log(' Screening...');
350
384
  await screenOrThrow(apiInstance, [walletAddress]);
351
385
 
@@ -664,6 +698,13 @@ OPTIONS:
664
698
  const sl = options['stop-loss'] !== undefined ? parsePositiveNumber(options['stop-loss'], 'stop-loss') : undefined;
665
699
  const isBuy = side === 'buy' || side === 'long';
666
700
 
701
+ // buildOrderAction re-checks this, but that call happens after the signing
702
+ // context is resolved and after ensureBuilderApproved has already signed
703
+ // and submitted the one-time builder-fee approval. A stop/take on the
704
+ // wrong side of entry would otherwise cost the user an on-chain approval
705
+ // and a password prompt for an order that was never valid.
706
+ validateTpsl({ isBuy, price, takeProfit: tp ?? null, stopLoss: sl ?? null });
707
+
667
708
  // One meta read serves both the advisory precision warning and the
668
709
  // required build metadata. Fetched fail-open so a meta outage doesn't
669
710
  // preempt a clearer error below (missing wallet, wrong password); we
package/src/privy.js CHANGED
@@ -10,6 +10,7 @@ import fs from "fs";
10
10
  import path from "path";
11
11
  import { parsePaymentRequirements } from "./x402.js";
12
12
  import { isEvmNetwork } from "./x402-evm.js";
13
+ import { mkdirPrivateSync, readWalletJson, writeWalletJsonAtomic } from "./wallet.js";
13
14
  import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo } from "./x402-policy.js";
14
15
  import {
15
16
  isSvmNetwork,
@@ -21,6 +22,7 @@ import {
21
22
  buildEIP712TypedData,
22
23
  buildPaymentSignatureHeader,
23
24
  } from "./walletconnect-x402.js";
25
+ import { trace } from "./debug.js";
24
26
 
25
27
  // ============= Constants =============
26
28
 
@@ -190,22 +192,20 @@ export async function createPrivyWalletPair(name) {
190
192
  createdAt: new Date().toISOString(),
191
193
  };
192
194
 
193
- if (!fs.existsSync(walletsDir)) {
194
- fs.mkdirSync(walletsDir, { mode: 0o700, recursive: true });
195
- }
195
+ mkdirPrivateSync(walletsDir);
196
196
 
197
197
  // Write config before wallet file so a crash doesn't leave an orphan without a default entry
198
198
  const configPath = path.join(walletsDir, "config.json");
199
199
  let config = { defaultWallet: null, passwordHash: null };
200
200
  if (fs.existsSync(configPath)) {
201
- config = JSON.parse(fs.readFileSync(configPath, "utf8"));
201
+ config = readWalletJson(configPath);
202
202
  }
203
203
  if (!config.defaultWallet) {
204
204
  config.defaultWallet = name;
205
- fs.writeFileSync(configPath, JSON.stringify(config, null, 2), { mode: 0o600 });
205
+ writeWalletJsonAtomic(configPath, config);
206
206
  }
207
207
 
208
- fs.writeFileSync(walletFile, JSON.stringify(walletData, null, 2), { mode: 0o600 });
208
+ writeWalletJsonAtomic(walletFile, walletData);
209
209
 
210
210
  return walletData;
211
211
  }
@@ -226,11 +226,11 @@ async function getPrivyEvmWallet(client) {
226
226
  const walletsDir = path.join(process.env.HOME || process.env.USERPROFILE || "", ".nansen", "wallets");
227
227
  const configPath = path.join(walletsDir, "config.json");
228
228
  if (fs.existsSync(configPath)) {
229
- const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
229
+ const config = readWalletJson(configPath);
230
230
  if (config.defaultWallet) {
231
231
  const walletFile = path.join(walletsDir, `${config.defaultWallet}.json`);
232
232
  if (fs.existsSync(walletFile)) {
233
- const data = JSON.parse(fs.readFileSync(walletFile, "utf8"));
233
+ const data = readWalletJson(walletFile);
234
234
  if (data.provider === "privy" && data.evm?.privyWalletId) {
235
235
  return client.getWallet(data.evm.privyWalletId);
236
236
  }
@@ -239,7 +239,7 @@ async function getPrivyEvmWallet(client) {
239
239
  }
240
240
  } catch (err) {
241
241
  // Fall through to list-based detection
242
- if (process.env.DEBUG) console.error(`[x402] Default wallet lookup failed: ${err.message}`);
242
+ trace("x402.default_wallet_lookup_failed", { error: err.message });
243
243
  }
244
244
 
245
245
  const result = await client.listWallets();
@@ -257,11 +257,11 @@ async function getPrivySolanaWallet(client) {
257
257
  const walletsDir = path.join(process.env.HOME || process.env.USERPROFILE || "", ".nansen", "wallets");
258
258
  const configPath = path.join(walletsDir, "config.json");
259
259
  if (fs.existsSync(configPath)) {
260
- const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
260
+ const config = readWalletJson(configPath);
261
261
  if (config.defaultWallet) {
262
262
  const walletFile = path.join(walletsDir, `${config.defaultWallet}.json`);
263
263
  if (fs.existsSync(walletFile)) {
264
- const data = JSON.parse(fs.readFileSync(walletFile, "utf8"));
264
+ const data = readWalletJson(walletFile);
265
265
  if (data.provider === "privy" && data.solana?.privyWalletId) {
266
266
  return client.getWallet(data.solana.privyWalletId);
267
267
  }
@@ -269,7 +269,7 @@ async function getPrivySolanaWallet(client) {
269
269
  }
270
270
  }
271
271
  } catch (err) {
272
- if (process.env.DEBUG) console.error(`[x402] Solana wallet lookup failed: ${err.message}`);
272
+ trace("x402.solana_wallet_lookup_failed", { error: err.message });
273
273
  }
274
274
 
275
275
  const result = await client.listWallets();