nansen-cli 2.0.0 → 2.1.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 (55) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +37 -9
  3. package/docs/browser-login.md +13 -7
  4. package/package.json +2 -2
  5. package/scripts/postinstall.js +1 -1
  6. package/skills/nansen-agent-guide/SKILL.md +3 -3
  7. package/skills/nansen-alerts-webhook-listener/SKILL.md +1 -1
  8. package/skills/nansen-dca-tracker/SKILL.md +1 -1
  9. package/skills/nansen-defi-positions/SKILL.md +1 -1
  10. package/skills/nansen-exit-signals/SKILL.md +1 -1
  11. package/skills/nansen-fund-tracker/SKILL.md +1 -1
  12. package/skills/nansen-general-search/SKILL.md +1 -1
  13. package/skills/nansen-holder-analysis/SKILL.md +1 -1
  14. package/skills/nansen-limit-orders/SKILL.md +1 -1
  15. package/skills/nansen-perp-screener/SKILL.md +1 -1
  16. package/skills/nansen-perp-trader-profile/SKILL.md +1 -1
  17. package/skills/nansen-polymarket-deep-dive/SKILL.md +1 -1
  18. package/skills/nansen-polymarket-insider-scan/SKILL.md +1 -1
  19. package/skills/nansen-polymarket-trader-profile/SKILL.md +1 -1
  20. package/skills/nansen-portfolio-tracker/SKILL.md +1 -1
  21. package/skills/nansen-prediction-markets/SKILL.md +1 -1
  22. package/skills/nansen-sm-cross-chain-flows/SKILL.md +1 -1
  23. package/skills/nansen-smart-alerts/SKILL.md +1 -1
  24. package/skills/nansen-smart-money-alpha/SKILL.md +1 -1
  25. package/skills/nansen-smart-money-tracker/SKILL.md +1 -1
  26. package/skills/nansen-smart-money-trend/SKILL.md +1 -1
  27. package/skills/nansen-token-research/SKILL.md +1 -1
  28. package/skills/nansen-token-screener/SKILL.md +1 -1
  29. package/skills/nansen-token-transfer-analysis/SKILL.md +1 -1
  30. package/skills/nansen-trading/SKILL.md +1 -1
  31. package/skills/nansen-wallet-batch/SKILL.md +1 -1
  32. package/skills/nansen-wallet-clustering/SKILL.md +1 -1
  33. package/skills/nansen-wallet-deep-dive/SKILL.md +1 -1
  34. package/skills/nansen-wallet-keychain-migration/SKILL.md +1 -1
  35. package/skills/nansen-wallet-manager/SKILL.md +1 -1
  36. package/skills/nansen-wallet-profiler/SKILL.md +1 -1
  37. package/skills/nansen-web-fetcher/SKILL.md +1 -1
  38. package/skills/nansen-web-searcher/SKILL.md +1 -1
  39. package/src/auth-credentials.js +16 -4
  40. package/src/auth-device.js +1 -1
  41. package/src/auth-login.js +4 -5
  42. package/src/auth-state.js +10 -8
  43. package/src/auth-store-worker.js +4 -3
  44. package/src/auto-paginate.js +31 -15
  45. package/src/bridge.js +105 -77
  46. package/src/cache-inspect.js +3 -7
  47. package/src/cli.js +13 -12
  48. package/src/doctor.js +1 -1
  49. package/src/limit-order.js +1 -1
  50. package/src/local-file.js +75 -0
  51. package/src/schema.json +28 -3
  52. package/src/solana-tx.js +74 -0
  53. package/src/trading.js +76 -40
  54. package/src/wallet.js +16 -35
  55. package/src/x402-svm.js +165 -7
package/src/bridge.js CHANGED
@@ -9,11 +9,13 @@
9
9
  import * as crypto from 'node:crypto';
10
10
  import * as fs from 'node:fs';
11
11
  import * as path from 'node:path';
12
+ import { readLocalFile, writeLocalFile } from './local-file.js';
12
13
 
13
14
  import { CommandError, validateAddress } from './api.js';
14
15
  import { signSecp256k1 } from './crypto.js';
15
16
  import {
16
17
  assertEvmFeeWithinCap,
18
+ claimQuoteForExecution,
17
19
  convertToBaseUnits,
18
20
  evmRpcCall,
19
21
  getEvmNonce,
@@ -242,11 +244,19 @@ function saveBridgeQuote(response, originChain, destinationChain, walletProvider
242
244
  }
243
245
 
244
246
  export function loadBridgeQuote(quoteId) {
247
+ const claimedPath = safeQuotesPath(`${quoteId}.executing.json`);
248
+ if (claimedPath && fs.lstatSync(claimedPath, { throwIfNoEntry: false })) {
249
+ throw new Error(`Bridge quote "${quoteId}" is claimed by another execution. Funds may be in flight. Check "nansen bridge status" before requesting a new quote.`);
250
+ }
245
251
  const filePath = safeQuotesPath(`${quoteId}.json`);
246
252
  if (!filePath || !fs.existsSync(filePath)) {
247
253
  throw new Error(`Bridge quote "${quoteId}" not found. Quotes expire after 1 hour.`);
248
254
  }
249
- const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
255
+ return readBridgeQuoteFile(filePath, quoteId);
256
+ }
257
+
258
+ function readBridgeQuoteFile(filePath, quoteId) {
259
+ const data = JSON.parse(readLocalFile(filePath, { root: path.dirname(getQuotesDir()) }));
250
260
  if (Date.now() - data.timestamp > QUOTE_TTL_MS) {
251
261
  fs.unlinkSync(filePath);
252
262
  throw new Error('Bridge quote has expired. Please request a new quote.');
@@ -289,10 +299,15 @@ export function loadBridgeQuote(quoteId) {
289
299
  // later step throwing must not leave the quote reusable. The step counters make
290
300
  // a partial failure legible to the operator (see loadBridgeQuote).
291
301
  export function markBridgeQuoteExecuted(quoteId, progress = {}) {
292
- const filePath = safeQuotesPath(`${quoteId}.json`);
293
- if (!filePath || !fs.existsSync(filePath)) return;
302
+ const claimedPath = safeQuotesPath(`${quoteId}.executing.json`);
303
+ const filePath = claimedPath && fs.lstatSync(claimedPath, { throwIfNoEntry: false })
304
+ ? claimedPath : safeQuotesPath(`${quoteId}.json`);
294
305
  try {
295
- const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
306
+ if (!filePath || !fs.existsSync(filePath)) {
307
+ if (progress.required) throw new Error('Missing execution state');
308
+ return;
309
+ }
310
+ const data = JSON.parse(readLocalFile(filePath, { root: path.dirname(getQuotesDir()) }));
296
311
  data.executedAt = data.executedAt || Date.now();
297
312
  if (progress.broadcast) {
298
313
  data.broadcasts = [...(data.broadcasts || []), { ...progress.broadcast, at: Date.now() }];
@@ -301,11 +316,9 @@ export function markBridgeQuoteExecuted(quoteId, progress = {}) {
301
316
  data.broadcastSteps = Math.max(data.broadcastSteps || 0, progress.broadcastSteps);
302
317
  }
303
318
  if (progress.totalSteps !== undefined) data.totalSteps = progress.totalSteps;
304
- fs.writeFileSync(filePath, JSON.stringify(data, null, 2), { mode: 0o600 });
319
+ writeLocalFile(filePath, JSON.stringify(data, null, 2), { root: path.dirname(getQuotesDir()) });
305
320
  } catch {
306
- // Best-effort: if the marker can't be written, the next execute attempt
307
- // will still proceed, but that's preferable to crashing after a successful
308
- // broadcast.
321
+ throw new CommandError('Could not safely record bridge execution. Funds may already be in flight. The quote remains claimed; check "nansen bridge status" before requesting a new quote.', 'QUOTE_STATE_UNSAFE');
309
322
  }
310
323
  }
311
324
 
@@ -2043,90 +2056,105 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
2043
2056
  preflightResult ??= await preflightPlan();
2044
2057
  const { evmIntent, hlIntent } = preflightResult;
2045
2058
 
2046
- // Consume the quote at each INDIVIDUAL broadcast, before any receipt wait.
2047
- // A tx can be accepted by the network and then have waitForReceipt time
2048
- // out; if the quote were still unspent, a retry would re-sign and re-send
2049
- // it with a fresh nonce. markBridgeQuoteExecuted pins executedAt on the
2050
- // first call, so the quote is spent the instant anything is in flight.
2051
- const onBroadcast = (stepId, txHash) =>
2052
- markBridgeQuoteExecuted(quoteId, {
2053
- broadcast: { step: stepId, txHash: txHash || null },
2054
- totalSteps: steps.length,
2055
- });
2056
-
2057
- // Step-level counter, recorded only once a step fully completes.
2058
- const markBroadcast = (index) =>
2059
- markBridgeQuoteExecuted(quoteId, {
2060
- broadcastSteps: index + 1,
2061
- totalSteps: steps.length,
2062
- });
2063
-
2064
- if (execution_type === 'evm_transaction') {
2065
- // Overrides move real money differently from what was quoted, so say so
2066
- // rather than letting them apply silently.
2067
- if (overridesSummary) {
2068
- log(` Overrides: ${overridesSummary}`);
2059
+ const claim = claimQuoteForExecution(quoteId, readBridgeQuoteFile);
2060
+ let handedOff = false;
2061
+ let keepClaimed = false;
2062
+ try {
2063
+ if (JSON.stringify(claim.quote) !== JSON.stringify(quoteData)) {
2064
+ throw new CommandError('Bridge quote changed while awaiting execution. Request a fresh quote.', 'QUOTE_STATE_UNSAFE');
2069
2065
  }
2070
- for (const [index, step] of steps.entries()) {
2071
- await processEvmStep(step, {
2072
- chain: quoteData.originChain,
2073
- privateKeyHex: creds.privateKey,
2074
- signerAddress: signer.address,
2075
- log,
2076
- onBroadcast,
2077
- feeOverrides,
2078
- nonceSequence,
2079
- intent: evmIntent,
2066
+ // Consume the quote at each INDIVIDUAL broadcast, before any receipt wait.
2067
+ // A tx can be accepted by the network and then have waitForReceipt time
2068
+ // out; if the quote were still unspent, a retry would re-sign and re-send
2069
+ // it with a fresh nonce. markBridgeQuoteExecuted pins executedAt on the
2070
+ // first call, so the quote is spent the instant anything is in flight.
2071
+ const onBroadcast = (stepId, txHash) => {
2072
+ handedOff = true;
2073
+ markBridgeQuoteExecuted(quoteId, {
2074
+ required: true,
2075
+ broadcast: { step: stepId, txHash: txHash || null },
2076
+ totalSteps: steps.length,
2080
2077
  });
2081
- markBroadcast(index);
2082
- }
2083
- } else if (execution_type === 'hyperliquid_signature') {
2084
- if (creds.provider === 'privy') {
2085
- const { PrivyClient } = await import('./privy.js');
2086
- const privyClient = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
2087
- for (const [index, step] of steps.entries()) {
2088
- await processSignatureStepPrivy(step, {
2089
- privyClient,
2090
- // `signer` above — the same resolution that was screened and
2091
- // matched against the quote, rather than resolving a second time.
2092
- walletId: signer.privyWalletIds?.evm,
2093
- log,
2094
- apiInstance,
2095
- onBroadcast,
2096
- intent: hlIntent,
2097
- });
2098
- markBroadcast(index);
2078
+ };
2079
+
2080
+ // Step-level counter, recorded only once a step fully completes.
2081
+ const markBroadcast = (index) =>
2082
+ markBridgeQuoteExecuted(quoteId, {
2083
+ required: true,
2084
+ broadcastSteps: index + 1,
2085
+ totalSteps: steps.length,
2086
+ });
2087
+
2088
+ if (execution_type === 'evm_transaction') {
2089
+ // Overrides move real money differently from what was quoted, so say so
2090
+ // rather than letting them apply silently.
2091
+ if (overridesSummary) {
2092
+ log(` Overrides: ${overridesSummary}`);
2099
2093
  }
2100
- } else {
2101
2094
  for (const [index, step] of steps.entries()) {
2102
- await processSignatureStepLocal(step, {
2095
+ await processEvmStep(step, {
2096
+ chain: quoteData.originChain,
2103
2097
  privateKeyHex: creds.privateKey,
2098
+ signerAddress: signer.address,
2104
2099
  log,
2105
- apiInstance,
2106
2100
  onBroadcast,
2107
- intent: hlIntent,
2101
+ feeOverrides,
2102
+ nonceSequence,
2103
+ intent: evmIntent,
2108
2104
  });
2109
2105
  markBroadcast(index);
2110
2106
  }
2107
+ } else if (execution_type === 'hyperliquid_signature') {
2108
+ if (creds.provider === 'privy') {
2109
+ const { PrivyClient } = await import('./privy.js');
2110
+ const privyClient = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
2111
+ for (const [index, step] of steps.entries()) {
2112
+ await processSignatureStepPrivy(step, {
2113
+ privyClient,
2114
+ // `signer` above — the same resolution that was screened and
2115
+ // matched against the quote, rather than resolving a second time.
2116
+ walletId: signer.privyWalletIds?.evm,
2117
+ log,
2118
+ apiInstance,
2119
+ onBroadcast,
2120
+ intent: hlIntent,
2121
+ });
2122
+ markBroadcast(index);
2123
+ }
2124
+ } else {
2125
+ for (const [index, step] of steps.entries()) {
2126
+ await processSignatureStepLocal(step, {
2127
+ privateKeyHex: creds.privateKey,
2128
+ log,
2129
+ apiInstance,
2130
+ onBroadcast,
2131
+ intent: hlIntent,
2132
+ });
2133
+ markBroadcast(index);
2134
+ }
2135
+ }
2136
+ } else {
2137
+ throw new Error(`Unknown execution type: ${execution_type}`);
2111
2138
  }
2112
- } else {
2113
- throw new Error(`Unknown execution type: ${execution_type}`);
2114
- }
2115
2139
 
2116
- // Every step is out; the marker above already consumed the quote.
2117
- markBridgeQuoteExecuted(quoteId, { broadcastSteps: steps.length, totalSteps: steps.length });
2140
+ // Every step is out; the marker above already consumed the quote.
2141
+ markBridgeQuoteExecuted(quoteId, { required: true, broadcastSteps: steps.length, totalSteps: steps.length });
2118
2142
 
2119
- log(`\n Bridge submitted. Polling for completion...`);
2120
- const status = await pollBridgeCompletion(apiInstance, { requestId: request_id, log });
2143
+ log(`\n Bridge submitted. Polling for completion...`);
2144
+ const status = await pollBridgeCompletion(apiInstance, { requestId: request_id, log });
2121
2145
 
2122
- if (status.status === 'success') {
2123
- log(`\n Bridge completed!`);
2124
- if (status.destination_tx_hashes?.length) {
2125
- log(` Destination tx: ${status.destination_tx_hashes[0]}`);
2146
+ if (status.status === 'success') {
2147
+ log(`\n Bridge completed!`);
2148
+ if (status.destination_tx_hashes?.length) {
2149
+ log(` Destination tx: ${status.destination_tx_hashes[0]}`);
2150
+ }
2126
2151
  }
2127
- }
2128
- log('');
2129
- return undefined;
2152
+ log('');
2153
+ return undefined;
2154
+ } catch (error) {
2155
+ keepClaimed = handedOff && error.code === 'QUOTE_STATE_UNSAFE';
2156
+ throw error;
2157
+ } finally { claim.release({ handedOff, keepClaimed }); }
2130
2158
  },
2131
2159
 
2132
2160
  'status': async (args, apiInstance, flags, options) => {
@@ -21,6 +21,7 @@
21
21
 
22
22
  import fs from 'fs';
23
23
  import path from 'path';
24
+ import { openLocalFile } from './local-file.js';
24
25
 
25
26
  import { getCacheDir, getConfigDir, DEFAULT_CACHE_TTL, NansenError, ErrorCode } from './api.js';
26
27
  import { getCostMapFile, COST_MAP_TTL_MS } from './cost-cache.js';
@@ -86,15 +87,10 @@ function readTimestamp(file, field) {
86
87
  let fd;
87
88
  let raw;
88
89
  try {
89
- // O_NOFOLLOW prevents a final-component symlink replacement after lstat.
90
- // Windows does not define it. There, only the earlier lstat check applies;
91
- // opening with O_RDONLY does not prevent this race.
92
- const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0);
93
- fd = fs.openSync(file, flags);
94
- if (!fs.fstatSync(fd).isFile()) return { raced: true };
90
+ fd = openLocalFile(file, { root: getConfigDir() });
95
91
  raw = fs.readFileSync(fd, 'utf8');
96
92
  } catch (error) {
97
- if (error?.code === 'ENOENT' || error?.code === 'ELOOP') return { raced: true };
93
+ if (error?.code === 'ENOENT' || error?.code === 'ELOOP' || error?.code === 'LOCAL_FILE_UNSAFE') return { raced: true };
98
94
  throw fsError('read', file, error);
99
95
  } finally {
100
96
  if (fd !== undefined) fs.closeSync(fd);
package/src/cli.js CHANGED
@@ -463,7 +463,7 @@ export function formatTable(data) {
463
463
  let records = located?.rows || [];
464
464
  if (!located && typeof data === 'object' && data !== null) {
465
465
  // Single object - convert to array
466
- records = [data];
466
+ records = [Array.isArray(data) ? { data } : data];
467
467
  }
468
468
 
469
469
  if (records.length === 0) {
@@ -527,7 +527,7 @@ export function formatCsv(data) {
527
527
  const located = locateRows(data, { descriptive: true });
528
528
  let records = located?.rows || [];
529
529
  if (!located && typeof data === 'object' && data !== null) {
530
- records = [data];
530
+ records = [Array.isArray(data) ? { data } : data];
531
531
  }
532
532
 
533
533
  if (records.length === 0) return '';
@@ -570,7 +570,7 @@ export function formatOutput(data, { pretty = false, table = false, csv = false
570
570
  if (data.success === false) {
571
571
  return { type: 'error', text: formatErrorText(data, { csv }) };
572
572
  }
573
- const body = data.data || data;
573
+ const body = Array.isArray(data.data) ? data : data.data || data;
574
574
  return csv
575
575
  ? { type: 'csv', text: formatCsv(body) }
576
576
  : { type: 'table', text: formatTable(body) };
@@ -1129,7 +1129,7 @@ AUTHENTICATION:
1129
1129
  Authentication failures never trigger payment; login verification and nansen account never auto-pay.
1130
1130
  Browser sessions renew automatically; uncertain renewal requires fresh login.
1131
1131
  Browser nansen:api sessions have API-key-equivalent account permissions; wallet signing is separate.
1132
- Browser login needs native storage and enabled server admission; release gates remain open.
1132
+ Browser login is enabled in production; saved sessions need native storage (see docs/browser-login.md).
1133
1133
  Public API endpoints keep their usual account, plan and credit checks; MCP key export is separate.
1134
1134
 
1135
1135
  TRADING:
@@ -1513,6 +1513,9 @@ export function buildCommands(deps = {}) {
1513
1513
  if (flags['api-key']) throw new CommandError('--api-key requires a value.', 'MISSING_PARAM');
1514
1514
  if ('api-key' in options && typeof options['api-key'] !== 'string') throw new CommandError('--api-key must be a single key string.', 'INVALID_PARAMS');
1515
1515
  if (!fromStdin && !flags.human && options['api-key'] === undefined) {
1516
+ if (!stdinTTY || !stdoutTTY) {
1517
+ throw new CommandError('Browser login requires an interactive terminal. In a headless environment, set NANSEN_API_KEY and run nansen login --human, or pipe a key to nansen login --api-key-stdin.', 'NOT_A_TTY');
1518
+ }
1516
1519
  return browserLoginFn({ flags, env, isTTY: stdoutTTY, log, errorOutput, state: authState });
1517
1520
  }
1518
1521
  if (flags['no-browser']) throw new CommandError('--no-browser cannot be combined with legacy key setup.', 'INVALID_PARAMS');
@@ -1598,12 +1601,10 @@ export function buildCommands(deps = {}) {
1598
1601
  } finally { await authState.finish(attempt); }
1599
1602
  const blankEnvKey = env.NANSEN_API_KEY !== undefined && !env.NANSEN_API_KEY.trim();
1600
1603
  if (fromStdin && flags.json) {
1601
- log(JSON.stringify({ event: 'saved', effective_source: env.NANSEN_API_KEY !== undefined ? 'env' : 'config', environment_key_blank: blankEnvKey, cleanup }));
1604
+ log(JSON.stringify({ event: 'saved', effective_source: blankEnvKey || env.NANSEN_API_KEY === undefined ? 'config' : 'env', environment_key_blank: blankEnvKey, cleanup }));
1602
1605
  return;
1603
1606
  }
1604
- if (env.NANSEN_API_KEY !== undefined) log(blankEnvKey
1605
- ? 'NANSEN_API_KEY is blank. Commands will fail until you unset it or supply a valid environment key.'
1606
- : 'Commands still use NANSEN_API_KEY. Unset it to use the saved credential.');
1607
+ if (env.NANSEN_API_KEY?.trim()) log('Commands still use NANSEN_API_KEY. Unset it to use the saved credential.');
1607
1608
 
1608
1609
  log(`✓ Saved to ${getConfigFileFn()}\n`);
1609
1610
  // Verification responses may reflect the submitted key. Stdin login
@@ -1614,7 +1615,7 @@ export function buildCommands(deps = {}) {
1614
1615
  if (!fromStdin && accountInfo?.credits_remaining !== undefined) {
1615
1616
  log(`Credits remaining: ${accountInfo.credits_remaining}`);
1616
1617
  }
1617
- log(blankEnvKey ? '\nUnset NANSEN_API_KEY to use the saved credential, then try:' : '\nYou can now use the Nansen CLI. Try:');
1618
+ log('\nYou can now use the Nansen CLI. Try:');
1618
1619
  log(' nansen research token screener --chain solana --pretty');
1619
1620
  },
1620
1621
 
@@ -1623,7 +1624,7 @@ export function buildCommands(deps = {}) {
1623
1624
  if (result.cleanup.some(item => item.local === 'incomplete')) log('Saved authentication selection cleared; secure-store deletion incomplete.');
1624
1625
  else log(result.removed ? 'Local credentials removed.' : 'No saved credentials found.');
1625
1626
  for (const message of cleanupMessage(result.cleanup)) log(message);
1626
- if (env.NANSEN_API_KEY !== undefined) log('Warning: NANSEN_API_KEY remains active. Run: unset NANSEN_API_KEY');
1627
+ if (env.NANSEN_API_KEY?.trim()) log('Warning: NANSEN_API_KEY remains active. Run: unset NANSEN_API_KEY');
1627
1628
  },
1628
1629
 
1629
1630
  'help': async (_args, _apiInstance, _flags, _options) => {
@@ -2522,8 +2523,8 @@ export async function runCLI(rawArgs, deps = {}) {
2522
2523
  const inputInteractiveDeps = {
2523
2524
  ...deps,
2524
2525
  isTTY: isInputTTY,
2525
- stdoutTTY: isTTY,
2526
- stdinTTY: isInputTTY,
2526
+ stdoutTTY: isTTY === true,
2527
+ stdinTTY: isInputTTY === true,
2527
2528
  promptFn: deps.promptFn ?? prompt,
2528
2529
  confirmationPromptFn: deps.confirmationPromptFn ?? promptForConfirmation,
2529
2530
  confirmationLog: deps.confirmationLog ?? errorOutput,
package/src/doctor.js CHANGED
@@ -251,7 +251,7 @@ export function runDoctorChecks(deps = {}) {
251
251
  const auth = resolveAuthConfig(env, devConfigPath);
252
252
 
253
253
  // --- environment ---
254
- const requiredMajor = parseEngineMajor(engines?.node) ?? 20;
254
+ const requiredMajor = parseEngineMajor(engines?.node) ?? 22;
255
255
  const currentMajor = parseInt(nodeVersion.replace(/^v/, ''), 10);
256
256
  checks.push(currentMajor >= requiredMajor
257
257
  ? check('node-version', 'ok', `Node ${nodeVersion} (>= ${requiredMajor} required)`)
@@ -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,75 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ const unsafe = (file, reason) => Object.assign(new Error(`Refusing an unsafe local file at ${file}: ${reason}. Repair that path before retrying.`), { code: 'LOCAL_FILE_UNSAFE' });
5
+ const sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino;
6
+ function checkStat(stat, directory, privateFile, file) {
7
+ if (!stat || (directory ? !stat.isDirectory() : !stat.isFile())) throw unsafe(file, directory ? 'expected a directory without symlinks' : 'expected a regular file without symlinks');
8
+ if (!directory && stat.nlink !== 1) throw unsafe(file, 'file has unexpected hard links');
9
+ if (privateFile && process.platform !== 'win32') {
10
+ if (stat.mode & 0o022) throw unsafe(file, 'authentication path is writable by group or other users');
11
+ if (stat.uid !== process.getuid()) throw unsafe(file, 'authentication path belongs to another user');
12
+ }
13
+ }
14
+
15
+ // Non-private stores may use an intentionally symlinked storage root.
16
+ // Authentication and all components below either root must be link-free.
17
+ // Descriptor checks reject replacements before any bytes are read or written.
18
+ export function openLocalFile(file, { root, flags = fs.constants.O_RDONLY, mode = 0o600, privateFile = false, maxBytes = Infinity } = {}) {
19
+ const base = path.resolve(root);
20
+ const target = path.resolve(file);
21
+ const relative = path.relative(base, target);
22
+ if (!relative || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) throw unsafe(target, 'path is outside its storage root');
23
+ const directories = [base];
24
+ for (const part of relative.split(path.sep).slice(0, -1)) directories.push(path.join(directories.at(-1), part));
25
+ const directoryStat = (dir, i) => i === 0 && !privateFile ? fs.statSync(dir) : fs.lstatSync(dir);
26
+ const parents = directories.map((dir, i) => {
27
+ const stat = directoryStat(dir, i);
28
+ checkStat(stat, true, privateFile, dir);
29
+ return stat;
30
+ });
31
+ const before = fs.lstatSync(target, { throwIfNoEntry: false });
32
+ if (before) checkStat(before, false, privateFile, target);
33
+ let fd;
34
+ try {
35
+ fd = fs.openSync(target, flags | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0), mode);
36
+ const opened = fs.fstatSync(fd);
37
+ checkStat(opened, false, privateFile, target);
38
+ if (opened.size > maxBytes) throw unsafe(target, `file exceeds its ${maxBytes}-byte limit`);
39
+ if (before && !sameFile(before, opened)) throw Object.assign(unsafe(target, 'file was replaced while opening'), { localFileRace: true });
40
+ const after = fs.lstatSync(target);
41
+ checkStat(after, false, privateFile, target);
42
+ if (!sameFile(opened, after)) throw Object.assign(unsafe(target, 'file was replaced while opening'), { localFileRace: true });
43
+ directories.forEach((dir, i) => {
44
+ const stat = directoryStat(dir, i);
45
+ checkStat(stat, true, privateFile, dir);
46
+ if (!sameFile(parents[i], stat)) throw unsafe(dir, 'directory was replaced while opening');
47
+ });
48
+ return fd;
49
+ } catch (error) {
50
+ if (fd !== undefined) fs.closeSync(fd);
51
+ if (error.code === 'ELOOP') throw unsafe(target, 'file became a symbolic link while opening');
52
+ throw error;
53
+ }
54
+ }
55
+
56
+ export function readLocalFile(file, options) {
57
+ const fd = openLocalFile(file, options);
58
+ try { return fs.readFileSync(fd, 'utf8'); }
59
+ finally { fs.closeSync(fd); }
60
+ }
61
+
62
+ export function writeLocalFile(file, contents, options) {
63
+ const fd = openLocalFile(file, { ...options, flags: fs.constants.O_WRONLY });
64
+ try {
65
+ const bytes = Buffer.from(contents, 'utf8');
66
+ fs.ftruncateSync(fd, 0);
67
+ let offset = 0;
68
+ while (offset < bytes.length) {
69
+ const written = fs.writeSync(fd, bytes, offset, bytes.length - offset, offset);
70
+ if (!written) throw new Error('Could not write the local file.');
71
+ offset += written;
72
+ }
73
+ fs.fsyncSync(fd);
74
+ } finally { fs.closeSync(fd); }
75
+ }
package/src/schema.json CHANGED
@@ -2364,6 +2364,15 @@
2364
2364
  },
2365
2365
  "list": {
2366
2366
  "description": "List all wallets",
2367
+ "returns": [
2368
+ "wallets[].name",
2369
+ "wallets[].provider",
2370
+ "wallets[].evm",
2371
+ "wallets[].solana",
2372
+ "wallets[].createdAt",
2373
+ "wallets[].isDefault",
2374
+ "defaultWallet"
2375
+ ],
2367
2376
  "examples": [
2368
2377
  "nansen wallet list",
2369
2378
  "nansen wallet list --pretty"
@@ -2376,6 +2385,16 @@
2376
2385
  "description": "Wallet name"
2377
2386
  }
2378
2387
  },
2388
+ "returns": [
2389
+ "name",
2390
+ "provider",
2391
+ "evm",
2392
+ "solana",
2393
+ "createdAt",
2394
+ "isDefault",
2395
+ "privyWalletIds.evm",
2396
+ "privyWalletIds.solana"
2397
+ ],
2379
2398
  "examples": [
2380
2399
  "nansen wallet show <name>"
2381
2400
  ]
@@ -2409,7 +2428,7 @@
2409
2428
  ]
2410
2429
  },
2411
2430
  "export": {
2412
- "description": "Export private keys (redacted by default; pass --reveal or --file <path> for the actual keys)",
2431
+ "description": "Export private keys (redacted by default: returns the addresses as JSON with no keys; pass --reveal or --file <path> for the actual keys)",
2413
2432
  "options": {
2414
2433
  "reveal": {
2415
2434
  "type": "boolean",
@@ -2420,6 +2439,12 @@
2420
2439
  "description": "Write private keys to this path instead of stdout (created with 0600 permissions, refuses to overwrite)"
2421
2440
  }
2422
2441
  },
2442
+ "returns": [
2443
+ "name",
2444
+ "redacted",
2445
+ "evm.address",
2446
+ "solana.address"
2447
+ ],
2423
2448
  "examples": [
2424
2449
  "nansen wallet export <name>",
2425
2450
  "nansen wallet export <name> --file backup.json"
@@ -2690,7 +2715,7 @@
2690
2715
  }
2691
2716
  },
2692
2717
  "login": {
2693
- "description": "Fresh browser approval in every starting state for API-key-equivalent account API permissions (nansen:api). Wallet signing and MCP key export remain separate. Plain login never persists NANSEN_API_KEY; it still overrides commands. Selected sessions renew automatically; uncertain renewal requires fresh login. Native custody and enabled server admission required; release acceptance pending.",
2718
+ "description": "Fresh browser approval in every starting state for API-key-equivalent account API permissions (nansen:api). Wallet signing and MCP key export remain separate. Plain login never persists NANSEN_API_KEY; it still overrides commands. Selected sessions renew automatically; uncertain renewal requires fresh login. Browser login is enabled in production; saved sessions need native storage (see docs/browser-login.md).",
2694
2719
  "options": {
2695
2720
  "no-browser": {
2696
2721
  "type": "boolean",
@@ -2698,7 +2723,7 @@
2698
2723
  },
2699
2724
  "json": {
2700
2725
  "type": "boolean",
2701
- "description": "Browser login: NDJSON pending and one terminal event; automatic in non-TTY. With --api-key-stdin: one saved event with effective_source, environment_key_blank and cleanup."
2726
+ "description": "Browser login: NDJSON pending and one terminal event with an interactive terminal; non-TTY exits with a JSON error envelope whose code is NOT_A_TTY. With --api-key-stdin: one saved event with effective_source, environment_key_blank and cleanup."
2702
2727
  },
2703
2728
  "human": {
2704
2729
  "type": "boolean",
package/src/solana-tx.js CHANGED
@@ -151,3 +151,77 @@ export function resolveStaticAccount(parsed, index) {
151
151
  if (index < parsed.staticAccountKeys.length) return parsed.staticAccountKeys[index];
152
152
  return null;
153
153
  }
154
+
155
+ // Owner of every address-lookup-table account.
156
+ export const ADDRESS_LOOKUP_TABLE_PROGRAM = 'AddressLookupTab1e1111111111111111111111111';
157
+ // LookupTableMeta: typeIndex u32, deactivationSlot u64, lastExtendedSlot u64,
158
+ // lastExtendedSlotStartIndex u8, authority Option<Pubkey>, padding. The
159
+ // 32-byte addresses start right after it.
160
+ // The program always reserves all 56 bytes, even when authority is None.
161
+ const LOOKUP_TABLE_META_SIZE = 56;
162
+ const LOOKUP_TABLE_TYPE_INDEX = 1;
163
+ // Lookups index a table with a single byte.
164
+ const LOOKUP_TABLE_MAX_ADDRESSES = 256;
165
+ // A table that has never been deactivated stores u64::MAX here.
166
+ const LOOKUP_TABLE_ACTIVE_SLOT = 0xffffffffffffffffn;
167
+ // The SlotHashes sysvar: the recent slots a deactivating table stays usable for.
168
+ export const SLOT_HASHES_SYSVAR = 'SysvarS1otHashes111111111111111111111111111';
169
+ export const SYSVAR_PROGRAM = 'Sysvar1111111111111111111111111111111111111';
170
+
171
+ /**
172
+ * Parse the raw data of an address-lookup-table account into its addresses and
173
+ * its deactivation slot (null when it has never been deactivated). Throws on
174
+ * anything that isn't an initialized table, so a truncated or foreign account
175
+ * can't be read as a short or shifted address list.
176
+ */
177
+ export function parseAddressLookupTable(data) {
178
+ if (data.length < LOOKUP_TABLE_META_SIZE || (data.length - LOOKUP_TABLE_META_SIZE) % 32 !== 0) {
179
+ throw new Error('Malformed address lookup table: unexpected account data length');
180
+ }
181
+ if ((data.length - LOOKUP_TABLE_META_SIZE) / 32 > LOOKUP_TABLE_MAX_ADDRESSES) {
182
+ throw new Error(`Malformed address lookup table: more than ${LOOKUP_TABLE_MAX_ADDRESSES} addresses`);
183
+ }
184
+ if (data.readUInt32LE(0) !== LOOKUP_TABLE_TYPE_INDEX) {
185
+ throw new Error('Malformed address lookup table: account is not an initialized lookup table');
186
+ }
187
+ const addresses = [];
188
+ for (let offset = LOOKUP_TABLE_META_SIZE; offset < data.length; offset += 32) {
189
+ addresses.push(base58Encode(data.subarray(offset, offset + 32)));
190
+ }
191
+ const deactivationSlot = data.readBigUInt64LE(4);
192
+ return {
193
+ deactivationSlot: deactivationSlot === LOOKUP_TABLE_ACTIVE_SLOT ? null : deactivationSlot,
194
+ addresses,
195
+ };
196
+ }
197
+
198
+ /**
199
+ * Parse the SlotHashes sysvar (u64 count, then count × (u64 slot, 32-byte
200
+ * hash)) into its slots.
201
+ */
202
+ export function parseSlotHashes(data) {
203
+ if (data.length < 8) throw new Error('Malformed SlotHashes sysvar: unexpected account data length');
204
+ const count = data.readBigUInt64LE(0);
205
+ if (8n + count * 40n > BigInt(data.length)) {
206
+ throw new Error('Malformed SlotHashes sysvar: unexpected account data length');
207
+ }
208
+ const slots = [];
209
+ for (let i = 0; i < Number(count); i++) slots.push(data.readBigUInt64LE(8 + i * 40));
210
+ return slots;
211
+ }
212
+
213
+ /**
214
+ * Whether the runtime still resolves addresses through a table, mirroring its
215
+ * LookupTableMeta status rule. Deactivating a table doesn't disable it at
216
+ * once: it stays usable while its deactivation slot is the current slot or is
217
+ * still in SlotHashes, and only then becomes deactivated.
218
+ *
219
+ * A deactivation slot past `currentSlot` also counts as usable. Our two RPC
220
+ * reads can come from nodes at different heights, and a slot we haven't seen
221
+ * yet can't have left SlotHashes.
222
+ */
223
+ export function isLookupTableUsable(deactivationSlot, currentSlot, slotHashes) {
224
+ if (deactivationSlot === null) return true;
225
+ if (deactivationSlot >= currentSlot) return true;
226
+ return slotHashes.includes(deactivationSlot);
227
+ }