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
@@ -15,6 +15,7 @@
15
15
  * EVM-only: Solana signs the aggregator transaction verbatim and is out of scope.
16
16
  */
17
17
 
18
+ import { AuthError } from './auth-credentials.js';
18
19
  import { SIMULATION_RPCS, isNansenHostedUrl } from './rpc-urls.js';
19
20
 
20
21
  // keccak256("Transfer(address,address,uint256)") — shared by ERC-20 and ERC-721.
@@ -202,30 +203,27 @@ function buildSimRpcBody(method, params) {
202
203
  return JSON.stringify({ jsonrpc: '2.0', id: 1, method, params });
203
204
  }
204
205
 
205
- async function postSim(rpcUrl, apiKey, method, params, timeoutMs) {
206
+ async function postSim(rpcUrl, auth, method, params, timeoutMs) {
206
207
  const controller = new AbortController();
207
208
  const timer = setTimeout(() => controller.abort(), timeoutMs);
208
209
  try {
209
- // Attach the Nansen API key ONLY when the endpoint is Nansen-hosted. A
210
- // NANSEN_BASE_SIM_RPC override can point at any host (dev node, third-party
211
- // trace RPC); forwarding the user's credential there would leak it, so an
212
- // untrusted endpoint is always called anonymously (see isNansenHostedUrl).
213
- const sendApiKey = Boolean(apiKey) && isNansenHostedUrl(rpcUrl);
210
+ // Resolve credentials only for the trusted Nansen origin. Custom RPCs
211
+ // remain anonymous and never open browser custody or receive its tokens.
212
+ const hosted = isNansenHostedUrl(rpcUrl);
213
+ let credentials = {};
214
+ if (hosted && auth.api) {
215
+ if (new URL(rpcUrl).origin !== auth.api.baseUrl) throw new AuthError('AUTH_ORIGIN_MISMATCH', 'Simulation origin differs from the selected API origin. Configure a matching Nansen simulation endpoint.');
216
+ credentials = await auth.api.requestCredentials();
217
+ }
214
218
  const res = await fetch(rpcUrl, {
215
219
  method: 'POST',
216
- // Refuse redirects only when the apikey header is attached — undici
217
- // forwards custom credential headers across a cross-origin redirect, so a
218
- // redirect would hand the key to whatever host the response points at.
219
- // An anonymous call to a user-configured third-party RPC carries nothing
220
- // to leak, so it keeps following redirects as before.
221
- redirect: sendApiKey ? 'error' : 'follow',
222
- headers: {
223
- 'Content-Type': 'application/json',
224
- ...(sendApiKey ? { apikey: apiKey } : {}),
225
- },
220
+ redirect: Object.keys(credentials).length ? 'error' : 'follow',
221
+ headers: { 'Content-Type': 'application/json', ...credentials },
226
222
  body: buildSimRpcBody(method, params),
227
223
  signal: controller.signal,
228
224
  });
225
+ // Anonymous simulation outages retain the existing warn-and-proceed policy.
226
+ if (hosted && auth.api && auth.api.selection.kind !== 'anonymous' && [401, 403].includes(res.status)) throw new AuthError('SIMULATION_ACCESS_DENIED', 'The selected account cannot access hosted simulation. Check account permissions or log in again.');
229
227
  const text = await res.text();
230
228
  let body;
231
229
  try {
@@ -254,7 +252,7 @@ async function postSim(rpcUrl, apiKey, method, params, timeoutMs) {
254
252
  }
255
253
  return body;
256
254
  } catch (e) {
257
- if (e instanceof SwapSimulationError) throw e;
255
+ if (e instanceof AuthError || e instanceof SwapSimulationError) throw e;
258
256
  if (e.name === 'AbortError') {
259
257
  throw new SwapSimulationError('SIM_RPC_ERROR', `Simulation RPC timed out after ${timeoutMs}ms (${method})`);
260
258
  }
@@ -304,7 +302,7 @@ function isRevertError(rpcError) {
304
302
  return (rpcError?.message || '').toLowerCase().includes('execution reverted');
305
303
  }
306
304
 
307
- async function simulateViaEthSimulateV1(rpcUrl, apiKey, { from, to, data, value }, timeoutMs) {
305
+ async function simulateViaEthSimulateV1(rpcUrl, auth, { from, to, data, value }, timeoutMs) {
308
306
  const params = [
309
307
  {
310
308
  blockStateCalls: [
@@ -319,7 +317,7 @@ async function simulateViaEthSimulateV1(rpcUrl, apiKey, { from, to, data, value
319
317
  },
320
318
  'latest',
321
319
  ];
322
- const body = await postSim(rpcUrl, apiKey, 'eth_simulateV1', params, timeoutMs);
320
+ const body = await postSim(rpcUrl, auth, 'eth_simulateV1', params, timeoutMs);
323
321
  if (body.error) {
324
322
  if (isMethodUnsupported(body.error)) {
325
323
  throw new SwapSimulationError('NOT_SIM_CAPABLE', `eth_simulateV1 unavailable: ${body.error.message}`);
@@ -368,13 +366,13 @@ function flattenFrames(root) {
368
366
  return { logs, frames };
369
367
  }
370
368
 
371
- async function simulateViaDebugTraceCall(rpcUrl, apiKey, { from, to, data, value }, timeoutMs) {
369
+ async function simulateViaDebugTraceCall(rpcUrl, auth, { from, to, data, value }, timeoutMs) {
372
370
  const params = [
373
371
  { from, to, data: data || '0x', value: value || '0x0' },
374
372
  'latest',
375
373
  { tracer: 'callTracer', tracerConfig: { withLog: true } },
376
374
  ];
377
- const body = await postSim(rpcUrl, apiKey, 'debug_traceCall', params, timeoutMs);
375
+ const body = await postSim(rpcUrl, auth, 'debug_traceCall', params, timeoutMs);
378
376
  if (body.error) {
379
377
  if (isMethodUnsupported(body.error)) {
380
378
  throw new SwapSimulationError('NOT_SIM_CAPABLE', `debug_traceCall unavailable: ${body.error.message}`);
@@ -455,11 +453,11 @@ async function simulateViaDebugTraceCall(rpcUrl, apiKey, { from, to, data, value
455
453
  *
456
454
  * @param {string} chain - chain key (only 'base' is wired today)
457
455
  * @param {{ to: string, data: string, value?: string }} swapCall - the swap tx
458
- * @param {{ from: string, apiKey?: string|null, timeoutMs?: number }} opts
456
+ * @param {{ from: string, api?: object, timeoutMs?: number }} opts
459
457
  * @returns {Promise<{ deltas: Record<string,bigint>, approvals: Array<{token,spender,amount}>, nftOut: Array<{standard,token}>, nftApprovals: Array<{standard,token,operator}>, method: string }>}
460
458
  * @throws {SwapSimulationError} on any degrade condition or an in-sim revert.
461
459
  */
462
- export async function simulateAssetChanges(chain, swapCall, { from, apiKey = null, timeoutMs = 20000 } = {}) {
460
+ export async function simulateAssetChanges(chain, swapCall, { from, api, timeoutMs = 20000 } = {}) {
463
461
  const rpcUrl = SIMULATION_RPCS[chain];
464
462
  if (!rpcUrl) {
465
463
  throw new SwapSimulationError('NO_SIM_RPC', `No simulation RPC configured for chain '${chain}'.`);
@@ -470,14 +468,21 @@ export async function simulateAssetChanges(chain, swapCall, { from, apiKey = nul
470
468
 
471
469
  const call = { from, to: swapCall.to, data: swapCall.data, value: swapCall.value };
472
470
 
473
- // Primary: eth_simulateV1 (native transfers as synthetic logs, single round
474
- // trip). Fall back to debug_traceCall only when eth_simulateV1 is unavailable.
471
+ // Primary and method fallback share credential selection, origin checks and
472
+ // error redaction. No transport failure changes account or payment rail.
475
473
  try {
476
- return await simulateViaEthSimulateV1(rpcUrl, apiKey, call, timeoutMs);
477
- } catch (e) {
478
- if (e instanceof SwapSimulationError && e.code === 'NOT_SIM_CAPABLE') {
479
- return await simulateViaDebugTraceCall(rpcUrl, apiKey, call, timeoutMs);
474
+ try {
475
+ return await simulateViaEthSimulateV1(rpcUrl, { api }, call, timeoutMs);
476
+ } catch (error) {
477
+ if (error instanceof SwapSimulationError && error.code === 'NOT_SIM_CAPABLE') {
478
+ return await simulateViaDebugTraceCall(rpcUrl, { api }, call, timeoutMs);
479
+ }
480
+ throw error;
481
+ }
482
+ } catch (error) {
483
+ if (api?.selection?.kind === 'session' && error instanceof SwapSimulationError) {
484
+ throw new SwapSimulationError(error.code, 'Simulation could not verify the swap. Check the selected account access and simulation service.');
480
485
  }
481
- throw e;
486
+ throw error;
482
487
  }
483
488
  }
package/src/telemetry.js CHANGED
@@ -241,6 +241,26 @@ function commandToPath(command) {
241
241
  return '/' + String(command).replace(/\s+/g, '/');
242
242
  }
243
243
 
244
+ // Authentication accepts positional extras for compatibility, but none of that
245
+ // input is analytics metadata. Keep this vocabulary closed on both outcomes.
246
+ const AUTH_FLAGS = new Set(['--human', '--api-key', '--api-key-stdin', '--no-browser', '--json']);
247
+ const AUTH_ERRORS = new Set(['PAIRING_CANCELLED', 'PAIRING_DENIED', 'PAIRING_EXPIRED', 'PAIRING_FAILED', 'AUTH_NETWORK_ERROR', 'AUTH_STORE_UNAVAILABLE', 'AUTH_LOCK_UNAVAILABLE', 'AUTH_BUSY', 'AUTH_TIMEOUT', 'AUTH_CANCELLED', 'AUTH_STATE_INVALID', 'AUTH_JOURNAL_INVALID', 'AUTH_CLEANUP_REQUIRED', 'AUTH_SELECTION_CHANGED', 'AUTH_ORIGIN_UNSUPPORTED', 'INVALID_BROWSER_SESSION', 'SESSION_VERIFICATION_FAILED', 'BROWSER_SESSION_SETUP_REQUIRED']);
248
+ export function trackAuthCommand({ command, duration_ms, flags = [], error_code, failed = false }) {
249
+ if (command !== 'login' && command !== 'logout') return Promise.resolve();
250
+ return sendEvent({
251
+ event: failed ? 'cli_command_failed' : 'cli_command_succeeded',
252
+ event_source: getEventSource(), event_id: crypto.randomUUID(), user_id: null,
253
+ anonymous_id: getAnonymousId(), session_id: getSessionId(),
254
+ timestamp: new Date().toISOString(), path: `/${command}`,
255
+ properties: {
256
+ source: `nansen-cli/${cliVersion}`, latency: duration_ms / 1000,
257
+ flags: [...new Set(flags.filter(flag => AUTH_FLAGS.has(flag)))],
258
+ ...(failed && { error_code: AUTH_ERRORS.has(error_code) ? error_code : 'AUTH_FAILED' }),
259
+ },
260
+ context: buildContext(),
261
+ });
262
+ }
263
+
244
264
  /**
245
265
  * Track a CLI command that completed successfully.
246
266
  *