nansen-cli 1.46.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 (77) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +129 -14
  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 +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 +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 +126 -21
  51. package/src/cache-inspect.js +345 -0
  52. package/src/cli.js +470 -197
  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/mcp-client-config.js +169 -0
  61. package/src/mcp-client-config.json +17 -0
  62. package/src/mcp-verify.js +6 -5
  63. package/src/perp.js +41 -0
  64. package/src/privy.js +12 -12
  65. package/src/response-meta.js +56 -1
  66. package/src/rpc-urls.js +9 -11
  67. package/src/schema.json +185 -8
  68. package/src/semver.js +23 -4
  69. package/src/swap-simulation.js +35 -30
  70. package/src/telemetry.js +20 -0
  71. package/src/trading.js +266 -29
  72. package/src/transfer.js +53 -6
  73. package/src/update-check.js +9 -1
  74. package/src/wallet.js +107 -17
  75. package/src/walletconnect-trading.js +24 -5
  76. package/src/x402-svm.js +123 -64
  77. package/src/x402.js +46 -14
package/src/bridge.js CHANGED
@@ -13,10 +13,12 @@ import * as path from 'node:path';
13
13
  import { CommandError, validateAddress } from './api.js';
14
14
  import { signSecp256k1 } from './crypto.js';
15
15
  import {
16
+ assertEvmFeeWithinCap,
16
17
  convertToBaseUnits,
17
18
  evmRpcCall,
18
19
  getEvmNonce,
19
20
  getQuotesDir,
21
+ parseMaxTxFeeOption,
20
22
  resolveUsdPrice,
21
23
  safeQuotesPath,
22
24
  signEvmTransaction,
@@ -707,12 +709,16 @@ const ERC20_APPROVE_SELECTOR = '0x095ea7b3';
707
709
  // Keyed by origin chain, in lockstep with the deposit rows of BRIDGE_ROUTES:
708
710
  // widening the EVM deposit side (a new signable origin chain) MUST add that
709
711
  // chain's router here too, or every deposit on the new route fails closed.
710
- const BRIDGE_DEPOSIT_TARGETS = {
712
+ // Exported for a CI guard test that pins every entry to a valid, lowercased
713
+ // 20-byte address — see the invariant note in assertEvmBridgeStepIntent's
714
+ // approve branch (a malformed entry would mis-code a spender-shape error as
715
+ // AMOUNT_MISMATCH, and a non-lowercased one would break the `.has()` lookups).
716
+ export const BRIDGE_DEPOSIT_TARGETS = {
711
717
  base: new Set(['0x4cd00e387622c35bddb9b4c962c136462338bc31']),
712
718
  };
713
719
 
714
720
  // The deposit call selector on that router. Its calldata is a fixed 4-arg ABI
715
- // layout: deposit(address depositor, address token, uint256 amount, bytes32 id).
721
+ // layout: depositErc20(address depositor, address token, uint256 amount, bytes32 id).
716
722
  const BRIDGE_DEPOSIT_SELECTOR = '0xe8017952';
717
723
 
718
724
  // True when calldata is an ERC-20 approve(spender, amount). 0x + 4-byte
@@ -758,14 +764,33 @@ function decodeBridgeDeposit(data) {
758
764
  // than a raw SyntaxError.
759
765
  return null;
760
766
  }
767
+ const idWord = w(3);
768
+ if (!/^[0-9a-fA-F]{64}$/.test(idWord)) return null;
761
769
  return {
762
770
  depositor: '0x' + w(0).slice(24), // last 20 bytes of word 0
763
771
  token: '0x' + w(1).slice(24),
764
772
  amount,
765
- // w(3) is the opaque relay id — intentionally not returned / not bound.
773
+ id: idWord, // opaque relay id word (bytes32), normalized on re-encode
766
774
  };
767
775
  }
768
776
 
777
+ // Re-encode accepted deposit calldata from decoded fields. Normalizes any dirty
778
+ // upper bits in address words (the decoded last-20-bytes are clean; padding them
779
+ // fresh means the output is canonical regardless of the input's upper bits).
780
+ // The relay id word is opaque — lowercased to canonical form; its value is
781
+ // preserved (a bytes32 is binary, so case carries no meaning on-chain).
782
+ // decodeBridgeDeposit already guarantees id is exactly 64 hex chars (it returns
783
+ // null unless data.length === 266 and the id word matches /^[0-9a-fA-F]{64}$/),
784
+ // so the padStart below is a no-op today — kept for symmetry with the other
785
+ // words and to stay correct if that invariant is ever loosened.
786
+ function encodeBridgeDeposit({ depositor, token, amount, id }) {
787
+ return BRIDGE_DEPOSIT_SELECTOR
788
+ + depositor.slice(2).toLowerCase().padStart(64, '0')
789
+ + token.slice(2).toLowerCase().padStart(64, '0')
790
+ + amount.toString(16).padStart(64, '0')
791
+ + id.toLowerCase().padStart(64, '0');
792
+ }
793
+
769
794
  // Bind a server-supplied EVM bridge transaction to the user's intent before
770
795
  // signing. Static only, no RPC. Fails CLOSED — a missing anchor or an
771
796
  // unrecognized target is itself the signal to refuse.
@@ -788,12 +813,21 @@ function requireAmountAnchor(intent, context) {
788
813
  'AMOUNT_MISMATCH',
789
814
  );
790
815
  }
816
+ try {
817
+ return BigInt(intent.requestedAmountBaseUnits);
818
+ } catch {
819
+ throw new CommandError(
820
+ `${context}: reviewed amount ${intent.requestedAmountBaseUnits} is not a valid integer. Refusing to sign. Request a new quote.`,
821
+ 'AMOUNT_MISMATCH',
822
+ );
823
+ }
791
824
  }
792
825
 
793
826
  // Returns { data } — for an approve step, `data` is RE-ENCODED via
794
827
  // encodeApproveCalldata (rejects MAX_UINT256, caps to requestedAmountBaseUnits,
795
- // re-validates the spender width). For a deposit step, `data` is returned
796
- // unchanged after the to/selector allowlist AND the decoded-arg binding pass.
828
+ // re-validates the spender width). For a deposit step, `data` is the canonical
829
+ // re-encoding from encodeBridgeDeposit after the to/selector allowlist AND the
830
+ // decoded-arg binding pass (normalizes dirty upper bits in address words).
797
831
  export function assertEvmBridgeStepIntent(txData, intent, context = 'Bridge EVM step') {
798
832
  if (!txData || typeof txData !== 'object' || typeof txData.data !== 'string') {
799
833
  throw new CommandError(`${context}: no transaction data to verify. Request a new quote.`, 'INVALID_INPUT');
@@ -845,7 +879,6 @@ export function assertEvmBridgeStepIntent(txData, intent, context = 'Bridge EVM
845
879
 
846
880
  // AC1: ERC-20 approve → re-scope through the hardened encoder.
847
881
  if (isErc20Approve(txData.data)) {
848
- requireAmountAnchor(intent, context);
849
882
  // The approve call itself must target the origin chain's USDC contract —
850
883
  // otherwise a spender/amount that both look legitimate could still grant
851
884
  // the router an allowance over an unrelated token the wallet holds.
@@ -872,12 +905,30 @@ export function assertEvmBridgeStepIntent(txData, intent, context = 'Bridge EVM
872
905
  'UNEXPECTED_ACTION',
873
906
  );
874
907
  }
875
- // encodeApproveCalldata rejects >= MAX_UINT256 and amount > maxAllowance,
876
- // and re-validates the 20-byte spender width. Cap to the requested input.
877
- const scoped = encodeApproveCalldata(spender, amount, {
878
- maxAllowance: BigInt(intent.requestedAmountBaseUnits),
879
- });
880
- return { data: scoped };
908
+ // Cap to the requested input. The only errors encodeApproveCalldata can
909
+ // throw here are amount-related (zero, unlimited, over-cap): the spender is
910
+ // already validated against BRIDGE_DEPOSIT_TARGETS above, and amount was
911
+ // already parsed as a BigInt by decodeErc20Approve — so AMOUNT_MISMATCH is
912
+ // the correct code for everything that can actually reach the catch.
913
+ // NB: this rests on every BRIDGE_DEPOSIT_TARGETS entry being a valid 20-byte
914
+ // address. If one were ever a zero/malformed address, encodeApproveCalldata's
915
+ // assertValidApprovalSpender would throw a spender-shape error that this catch
916
+ // would mis-code as AMOUNT_MISMATCH — keep that constant's entries valid.
917
+ const maxAllowance = requireAmountAnchor(intent, context);
918
+ try {
919
+ const scoped = encodeApproveCalldata(spender, amount, { maxAllowance });
920
+ return { data: scoped };
921
+ } catch (err) {
922
+ // encodeApproveCalldata messages already end with their own imperative
923
+ // ("Refusing to sign[ an … approval].") — drop it so we don't stack two
924
+ // directives before appending the single actionable next step every
925
+ // sibling refusal ends with.
926
+ const reason = err.message.replace(/\s*Refusing to sign[^.]*\.\s*$/, '');
927
+ throw new CommandError(
928
+ `${context}: ${reason} Request a new quote.`,
929
+ 'AMOUNT_MISMATCH',
930
+ );
931
+ }
881
932
  }
882
933
 
883
934
  // AC2: deposit call → to + selector must both be on the route's allowlist.
@@ -925,8 +976,14 @@ export function assertEvmBridgeStepIntent(txData, intent, context = 'Bridge EVM
925
976
  }
926
977
  // arg2 (amount) must not exceed what the user requested (defense in depth —
927
978
  // the scoped approval already bounds the pull; captures show exact equality).
928
- requireAmountAnchor(intent, context);
929
- if (dep.amount > BigInt(intent.requestedAmountBaseUnits)) {
979
+ if (dep.amount <= 0n) {
980
+ throw new CommandError(
981
+ context + ' would deposit ' + dep.amount + '; deposit amount must be positive. Refusing to sign. Request a new quote.',
982
+ 'AMOUNT_MISMATCH',
983
+ );
984
+ }
985
+ const requestedAmount = requireAmountAnchor(intent, context);
986
+ if (dep.amount > requestedAmount) {
930
987
  throw new CommandError(
931
988
  `${context} would deposit ${dep.amount}, more than the ${intent.requestedAmountBaseUnits} base units you requested. `
932
989
  + `Refusing to sign. Request a new quote.`,
@@ -937,7 +994,7 @@ export function assertEvmBridgeStepIntent(txData, intent, context = 'Bridge EVM
937
994
  // appears on-chain — both are the accepted relayer-trust residual, bounded by
938
995
  // the checks above.
939
996
 
940
- return { data: txData.data };
997
+ return { data: encodeBridgeDeposit(dep) };
941
998
  }
942
999
 
943
1000
  // Validate every EVM step's calldata against intent BEFORE any step is signed
@@ -961,14 +1018,26 @@ export function assertEvmBridgeStepIntent(txData, intent, context = 'Bridge EVM
961
1018
  export function preflightEvmBridgeSteps(steps, intent) {
962
1019
  let approveCount = 0;
963
1020
  let depositCount = 0;
1021
+ let sawDeposit = false;
964
1022
  for (const step of steps) {
965
1023
  for (const item of step.items || []) {
966
1024
  if (item.status === 'complete') continue; // don't re-check / re-count resumed steps
967
1025
  assertEvmBridgeStepIntent(item.data, intent, `Bridge step "${step.id}"`);
968
1026
  // assertEvmBridgeStepIntent above already proved each item is exactly one
969
1027
  // of these two shapes, so this classification is total.
970
- if (isErc20Approve(item.data.data)) approveCount++;
971
- else depositCount++;
1028
+ if (isErc20Approve(item.data.data)) {
1029
+ if (sawDeposit) {
1030
+ throw new CommandError(
1031
+ `Bridge plan has an incomplete approve transaction after the deposit; every incomplete approve must precede the deposit. `
1032
+ + `Refusing to sign — a trailing approve could leave a live router allowance after the deposit is already consumed. Request a new quote.`,
1033
+ 'UNEXPECTED_ACTION',
1034
+ );
1035
+ }
1036
+ approveCount++;
1037
+ } else {
1038
+ sawDeposit = true;
1039
+ depositCount++;
1040
+ }
972
1041
  }
973
1042
  }
974
1043
  if (approveCount > 1 || depositCount !== 1) {
@@ -1162,6 +1231,7 @@ async function processEvmStep(step, { chain, privateKeyHex, signerAddress, log,
1162
1231
  privateKeyHex,
1163
1232
  chain,
1164
1233
  nonce,
1234
+ { label: `bridge step "${step.id}"`, maxTxFeeWei: feeOverrides?.maxTxFeeWei },
1165
1235
  );
1166
1236
 
1167
1237
  log(` Broadcasting ${step.id} on ${chain}...`);
@@ -1616,6 +1686,17 @@ OPTIONS:
1616
1686
  ? resolveBridgeToken(toTokenRaw, destinationChain)
1617
1687
  : resolveBridgeToken('USDC', destinationChain);
1618
1688
 
1689
+ if (
1690
+ originChain === 'base'
1691
+ && destinationChain === 'hyperliquid'
1692
+ && !isBridgeUsdc(originToken, originChain)
1693
+ ) {
1694
+ throw new CommandError(
1695
+ 'Base -> Hyperliquid bridge deposits currently support USDC only. Use --from-token USDC.',
1696
+ 'INVALID_INPUT',
1697
+ );
1698
+ }
1699
+
1619
1700
  const wallet = resolveWalletAddress(walletName);
1620
1701
 
1621
1702
  // Default: --amount is base units. With --amount-unit, accept a human token
@@ -1741,6 +1822,8 @@ RECOVERY OPTIONS (EVM deposit legs only):
1741
1822
  --priority-fee Priority fee in gwei, overriding the quoted one
1742
1823
  --max-fee Fee cap in gwei, overriding the computed one
1743
1824
  --nonce Sign at this nonce instead of the next one
1825
+ --max-tx-fee Most one transaction may pay for gas (fee cap x gas limit),
1826
+ in ETH. Default 1; 0 disables the check.
1744
1827
 
1745
1828
  Use these to replace a transaction that is stuck in the mempool: a replacement
1746
1829
  must reuse the stuck nonce and outbid it (roughly +10%), and the fees computed
@@ -1755,6 +1838,11 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1755
1838
  // Fee/nonce overrides. Parsed before the quote is touched so a typo can't
1756
1839
  // consume it, and only applied to EVM legs — an HL withdrawal signs an
1757
1840
  // action with no fee fields at all.
1841
+ // A bare --max-tx-fee lands in flags, not options, so it would otherwise
1842
+ // read as "not given" and silently apply the default cap.
1843
+ if (flags['max-tx-fee']) {
1844
+ throw new CommandError('--max-tx-fee requires a value in ETH (e.g. 0.5), or 0 for no cap.', 'INVALID_INPUT');
1845
+ }
1758
1846
  const feeOverrides = {
1759
1847
  priorityFeeWei: options['priority-fee'] !== undefined
1760
1848
  ? parseGweiToWei(options['priority-fee'], 'priority-fee')
@@ -1762,6 +1850,7 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1762
1850
  maxFeeWei: options['max-fee'] !== undefined
1763
1851
  ? parseGweiToWei(options['max-fee'], 'max-fee')
1764
1852
  : null,
1853
+ maxTxFeeWei: parseMaxTxFeeOption(options['max-tx-fee']),
1765
1854
  };
1766
1855
  let nonceSequence = null;
1767
1856
  if (options.nonce !== undefined) {
@@ -1853,12 +1942,12 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1853
1942
  : [signerAddress];
1854
1943
  await screenOrThrow(apiInstance, screenAddresses);
1855
1944
 
1856
- // These checks need only the cached quote and public signer address. A
1945
+ // These checks use the quote, public signer address, and current EVM fees. A
1857
1946
  // dry run must execute them before returning at the gate; a real run
1858
1947
  // preserves the established password/error ordering by executing them
1859
1948
  // after credentials resolve. Cache the result so each invocation can run
1860
1949
  // the preflight at most once even if the guard's control flow changes.
1861
- const preflightPlan = () => {
1950
+ const preflightPlan = async () => {
1862
1951
  let evmIntent = null;
1863
1952
  let hlIntent = null;
1864
1953
  if (execution_type === 'evm_transaction') {
@@ -1868,6 +1957,22 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1868
1957
  requestedAmountBaseUnits: quoteData.requestedAmountBaseUnits ?? null,
1869
1958
  };
1870
1959
  preflightEvmBridgeSteps(steps, evmIntent);
1960
+ // Check the whole plan before an approval can spend gas or grant an
1961
+ // allowance. Match signing's fee resolution and numeric gas normalization;
1962
+ // the signer checks again if network fees change during execution.
1963
+ for (const step of steps) {
1964
+ for (const item of step.items || []) {
1965
+ if (item.status === 'complete') continue;
1966
+ const txData = item.data;
1967
+ const fees = await resolveEvmStepFees(evmIntent.chain, txData, feeOverrides);
1968
+ assertEvmFeeWithinCap(
1969
+ fees.maxFeePerGas || fees.gasPrice,
1970
+ BigInt(txData.gas || txData.gasLimit || '210000').toString(),
1971
+ `bridge step "${step.id}"`,
1972
+ feeOverrides.maxTxFeeWei,
1973
+ );
1974
+ }
1975
+ }
1871
1976
  } else if (execution_type === 'hyperliquid_signature') {
1872
1977
  const currencyIn = quoteData.response.details?.currencyIn;
1873
1978
  if (quoteData.requestedAmountBaseUnits != null && currencyIn?.amount != null) {
@@ -1909,7 +2014,7 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1909
2014
  // --yes/non-TTY retain the established ordering (credentials first,
1910
2015
  // preflight immediately before signing).
1911
2016
  const shouldPreflightPlan = guard.dryRun || (guard.isTTY && !guard.assumeYes);
1912
- let preflightResult = shouldPreflightPlan ? preflightPlan() : null;
2017
+ let preflightResult = shouldPreflightPlan ? await preflightPlan() : null;
1913
2018
 
1914
2019
  // ── Acknowledgement gate: --dry-run / --yes ──────────────────────
1915
2020
  // Placed before the signing credentials are loaded and well before the
@@ -1935,7 +2040,7 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1935
2040
  // different wallet than the one just screened if the default changed in
1936
2041
  // between.
1937
2042
  const creds = resolveSigningCredentials(signer);
1938
- preflightResult ??= preflightPlan();
2043
+ preflightResult ??= await preflightPlan();
1939
2044
  const { evmIntent, hlIntent } = preflightResult;
1940
2045
 
1941
2046
  // Consume the quote at each INDIVIDUAL broadcast, before any receipt wait.
@@ -0,0 +1,345 @@
1
+ /**
2
+ * Cache inspection and invalidation — the read and clear side of the caches
3
+ * the CLI already keeps under ~/.nansen. This module owns no cache of its own
4
+ * and never writes an entry; it only reports and deletes.
5
+ *
6
+ * responses ~/.nansen/cache/<digest>.json (api.js) TTL --cache-ttl, default 300s
7
+ * cost-map ~/.nansen/cost-map.json (cost-cache.js) TTL 24h
8
+ * update-check ~/.nansen/update-check.json (update-check.js) TTL 24h
9
+ *
10
+ * Privacy: stats extract each cache's timestamp metadata and never retain or
11
+ * render payload fields. Response cache filenames are digests of the request,
12
+ * and they are not printed either.
13
+ *
14
+ * Safety: clearing only ever unlinks regular files at the three paths above —
15
+ * `.json` entries directly inside the response cache directory, and the two
16
+ * named files. Directories and symlinks are skipped rather than followed, so a
17
+ * clear cannot reach outside the cache it was pointed at. Everything else under
18
+ * ~/.nansen (config.json, wallets/, quotes/, telemetry-id, saved auth) is never
19
+ * read or deleted by the inspector. CLI startup loads config separately.
20
+ */
21
+
22
+ import fs from 'fs';
23
+ import path from 'path';
24
+
25
+ import { getCacheDir, getConfigDir, DEFAULT_CACHE_TTL, NansenError, ErrorCode } from './api.js';
26
+ import { getCostMapFile, COST_MAP_TTL_MS } from './cost-cache.js';
27
+ import { getUpdateCheckFile, UPDATE_CHECK_TTL_MS } from './update-check.js';
28
+
29
+ const SECOND = 1000;
30
+ const RESPONSE_ENTRY = /^[0-9a-f]{64}\.json$/;
31
+
32
+ /** Cache names, in report order. */
33
+ export const CACHE_NAMES = ['responses', 'cost-map', 'update-check'];
34
+
35
+ /** Accepted `nansen cache clear` targets. */
36
+ export const CLEAR_TARGETS = [...CACHE_NAMES, 'all'];
37
+
38
+ /**
39
+ * Descriptors for the known caches. Built per call rather than once at import
40
+ * so the paths always come from the modules that own them.
41
+ */
42
+ function namespaces() {
43
+ return [
44
+ {
45
+ name: 'responses',
46
+ label: 'response cache',
47
+ description: 'API responses saved when --cache is passed',
48
+ kind: 'dir',
49
+ dirOrFile: getCacheDir(),
50
+ // The effective TTL is chosen per invocation by --cache-ttl.
51
+ ttlSeconds: null,
52
+ },
53
+ {
54
+ name: 'cost-map',
55
+ label: 'credit cost map',
56
+ description: 'per-endpoint credit costs used to report what a call cost',
57
+ kind: 'file',
58
+ dirOrFile: getCostMapFile(),
59
+ timestampField: 'fetchedAt',
60
+ ttlSeconds: COST_MAP_TTL_MS / SECOND,
61
+ },
62
+ {
63
+ name: 'update-check',
64
+ label: 'update check',
65
+ description: 'latest published CLI version, for the upgrade notice',
66
+ kind: 'file',
67
+ dirOrFile: getUpdateCheckFile(),
68
+ timestampField: 'checkedAt',
69
+ ttlSeconds: UPDATE_CHECK_TTL_MS / SECOND,
70
+ },
71
+ ];
72
+ }
73
+
74
+ /**
75
+ * Regular digest-named `.json` files directly inside `dir`, with size and,
76
+ * when requested, timestamp metadata. A missing directory is an empty cache,
77
+ * not an error. lstat (not stat) means symlinked entries are skipped; the
78
+ * directory itself is also rejected if it is a symlink.
79
+ */
80
+ function fsError(action, target, error) {
81
+ const detail = error?.code ? `[${error.code}] ${error.message}` : String(error);
82
+ return new Error(`Cannot ${action} cache path ${target}: ${detail}`);
83
+ }
84
+
85
+ function readTimestamp(file, field) {
86
+ let fd;
87
+ let raw;
88
+ 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 };
95
+ raw = fs.readFileSync(fd, 'utf8');
96
+ } catch (error) {
97
+ if (error?.code === 'ENOENT' || error?.code === 'ELOOP') return { raced: true };
98
+ throw fsError('read', file, error);
99
+ } finally {
100
+ if (fd !== undefined) fs.closeSync(fd);
101
+ }
102
+ try {
103
+ const value = JSON.parse(raw)?.[field];
104
+ // Auxiliary cache readers treat a zero timestamp as missing metadata.
105
+ const valid = Number.isFinite(value) && (field === 'timestamp' || value !== 0);
106
+ return { timestampMs: valid ? value : null };
107
+ } catch {
108
+ // A corrupt cache is dead to its owner and therefore already expired.
109
+ return { timestampMs: null };
110
+ }
111
+ }
112
+
113
+ function listDirEntries(dir, { readMetadata = false } = {}) {
114
+ let names;
115
+ try {
116
+ const dirStat = fs.lstatSync(dir);
117
+ if (dirStat.isSymbolicLink()) {
118
+ throw new Error(`Refusing to use symlinked response cache directory: ${dir}`);
119
+ }
120
+ if (!dirStat.isDirectory()) {
121
+ throw new Error(`Response cache path is not a directory: ${dir}`);
122
+ }
123
+ names = fs.readdirSync(dir);
124
+ } catch (error) {
125
+ if (error?.code === 'ENOENT') return [];
126
+ if (error?.message?.startsWith('Refusing') || error?.message?.startsWith('Response cache')) throw error;
127
+ throw fsError('list', dir, error);
128
+ }
129
+ const entries = [];
130
+ for (const name of names) {
131
+ // `name` comes from this directory's own listing, not from a caller. The
132
+ // strict digest shape both identifies files written by api.js and prevents
133
+ // path separators or traversal segments from reaching path.join(). The
134
+ // lstat below then rejects a final-component symlink before any read/delete.
135
+ if (!RESPONSE_ENTRY.test(name)) continue;
136
+ const file = path.join(dir, name);
137
+ try {
138
+ const stat = fs.lstatSync(file);
139
+ if (!stat.isFile()) continue;
140
+ const metadata = readMetadata ? readTimestamp(file, 'timestamp') : {};
141
+ if (metadata.raced) continue;
142
+ entries.push({ file, bytes: stat.size, ...metadata });
143
+ } catch (error) {
144
+ if (error?.code === 'ENOENT') continue;
145
+ throw error;
146
+ }
147
+ }
148
+ return entries;
149
+ }
150
+
151
+ /** The single file of a one-file cache, or nothing if it is absent. */
152
+ function listFileEntry(file, timestampField, { readMetadata = false } = {}) {
153
+ try {
154
+ const stat = fs.lstatSync(file);
155
+ if (!stat.isFile()) return [];
156
+ const metadata = readMetadata ? readTimestamp(file, timestampField) : {};
157
+ if (metadata.raced) return [];
158
+ return [{ file, bytes: stat.size, ...metadata }];
159
+ } catch (error) {
160
+ if (error?.code === 'ENOENT') return [];
161
+ throw error;
162
+ }
163
+ }
164
+
165
+ function listEntries(ns, options) {
166
+ return ns.kind === 'dir'
167
+ ? listDirEntries(ns.dirOrFile, options)
168
+ : listFileEntry(ns.dirOrFile, ns.timestampField, options);
169
+ }
170
+
171
+ /**
172
+ * What every cache holds right now: entry count, bytes on disk, the age of the
173
+ * oldest and newest entry, the effective TTL, and how many entries are already
174
+ * past it. `responseTtlSeconds` is the TTL this invocation would apply
175
+ * (--cache-ttl), so the expiry count matches what the next call would see.
176
+ *
177
+ * @param {object} [options]
178
+ * @param {number} [options.responseTtlSeconds] Non-negative safe integer seconds.
179
+ * Invalid TTL values use DEFAULT_CACHE_TTL. Zero disables response cache reads.
180
+ * @param {number} [options.now] Safe integer milliseconds since the Unix epoch.
181
+ * Invalid clock values throw INVALID_PARAMS before any file access.
182
+ */
183
+ export function collectCacheStats({ responseTtlSeconds = DEFAULT_CACHE_TTL, now = Date.now() } = {}) {
184
+ if (!Number.isSafeInteger(responseTtlSeconds) || responseTtlSeconds < 0) {
185
+ responseTtlSeconds = DEFAULT_CACHE_TTL;
186
+ }
187
+ if (!Number.isSafeInteger(now)) {
188
+ throw new NansenError('now must be a safe integer timestamp in milliseconds.', ErrorCode.INVALID_PARAMS);
189
+ }
190
+
191
+ const caches = [];
192
+ let totalEntries = 0;
193
+ let totalBytes = 0;
194
+
195
+ for (const ns of namespaces()) {
196
+ const entries = listEntries(ns, { readMetadata: true });
197
+ const ttlSeconds = ns.name === 'responses' ? responseTtlSeconds : ns.ttlSeconds;
198
+ // A file stamped in the future (clock skew) is 0s old, never negative.
199
+ const rawAges = entries.map(e => e.timestampMs == null ? null : Math.max(0, (now - e.timestampMs) / SECOND));
200
+ let oldestAge = null;
201
+ let newestAge = null;
202
+ for (const age of rawAges) {
203
+ if (age == null) continue;
204
+ const roundedAge = Math.round(age);
205
+ oldestAge = oldestAge == null ? roundedAge : Math.max(oldestAge, roundedAge);
206
+ newestAge = newestAge == null ? roundedAge : Math.min(newestAge, roundedAge);
207
+ }
208
+ const bytes = entries.reduce((sum, e) => sum + e.bytes, 0);
209
+
210
+ totalEntries += entries.length;
211
+ totalBytes += bytes;
212
+
213
+ caches.push({
214
+ name: ns.name,
215
+ description: ns.description,
216
+ path: ns.dirOrFile,
217
+ entries: entries.length,
218
+ bytes,
219
+ ttl_seconds: ttlSeconds,
220
+ oldest_age_seconds: oldestAge,
221
+ newest_age_seconds: newestAge,
222
+ // Response reads allow an age equal to the TTL. Auxiliary caches refresh
223
+ // at that boundary. A response TTL of zero disables all cache reads.
224
+ expired_entries: rawAges.filter(age => (
225
+ age == null || ttlSeconds === 0 || (ns.kind === 'file' ? age >= ttlSeconds : age > ttlSeconds)
226
+ )).length,
227
+ });
228
+ }
229
+
230
+ return {
231
+ config_dir: getConfigDir(),
232
+ caches,
233
+ total_entries: totalEntries,
234
+ total_bytes: totalBytes,
235
+ // Hits and misses are decided in memory and nothing records them on disk,
236
+ // so there is no hit rate to report. Reported explicitly so the absence
237
+ // reads as a known fact rather than a missing field.
238
+ hit_miss_recorded: false,
239
+ };
240
+ }
241
+
242
+ /**
243
+ * Delete one cache, or all of them. Returns exactly what was removed so the
244
+ * caller can print it. An unknown target removes nothing.
245
+ */
246
+ export function clearCaches(target) {
247
+ if (!CLEAR_TARGETS.includes(target)) {
248
+ throw new NansenError(
249
+ `Unknown cache clear target: ${target}. Use one of: ${CLEAR_TARGETS.join(', ')}`,
250
+ ErrorCode.INVALID_PARAMS,
251
+ );
252
+ }
253
+
254
+ const wanted = target === 'all' ? CACHE_NAMES : [target];
255
+ const removed = [];
256
+ let totalEntries = 0;
257
+ let totalBytes = 0;
258
+
259
+ for (const ns of namespaces()) {
260
+ if (!wanted.includes(ns.name)) continue;
261
+ let entries = 0;
262
+ let bytes = 0;
263
+ for (const entry of listEntries(ns, { readMetadata: false })) {
264
+ try {
265
+ fs.unlinkSync(entry.file);
266
+ } catch (error) {
267
+ if (error?.code === 'ENOENT') continue;
268
+ throw fsError('delete', entry.file, error);
269
+ }
270
+ entries += 1;
271
+ bytes += entry.bytes;
272
+ }
273
+ totalEntries += entries;
274
+ totalBytes += bytes;
275
+ removed.push({ name: ns.name, label: ns.label, path: ns.dirOrFile, entries, bytes });
276
+ }
277
+
278
+ return { target, removed, total_entries: totalEntries, total_bytes: totalBytes };
279
+ }
280
+
281
+ // ============= Rendering =============
282
+
283
+ export function formatBytes(bytes) {
284
+ if (bytes < 1024) return `${bytes} B`;
285
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
286
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
287
+ }
288
+
289
+ export function formatAge(seconds) {
290
+ if (seconds == null) return '-';
291
+ if (seconds < 60) return `${seconds}s`;
292
+ if (seconds < 3600) return `${Math.round(seconds / 60)}m`;
293
+ // Hours up to two days: a 24h TTL reads better as "24h" than as "1d".
294
+ if (seconds < 172800) return `${Math.round(seconds / 3600)}h`;
295
+ return `${Math.round(seconds / 86400)}d`;
296
+ }
297
+
298
+ function entryCount(count) {
299
+ return `${count} ${count === 1 ? 'entry' : 'entries'}`;
300
+ }
301
+
302
+ /**
303
+ * Human-readable stats. Deliberately aggregate-only: no filenames, no endpoint
304
+ * paths, no parameters, nothing read out of a cached payload.
305
+ */
306
+ export function formatCacheStats(stats) {
307
+ const lines = ['Cache stats', ''];
308
+
309
+ for (const cache of stats.caches) {
310
+ const cols = [
311
+ cache.name.padEnd(13),
312
+ entryCount(cache.entries).padStart(10),
313
+ formatBytes(cache.bytes).padStart(9),
314
+ `TTL ${formatAge(cache.ttl_seconds)}`.padEnd(8),
315
+ ];
316
+ if (cache.entries > 0) {
317
+ cols.push(`oldest ${formatAge(cache.oldest_age_seconds)}`.padEnd(12));
318
+ cols.push(`newest ${formatAge(cache.newest_age_seconds)}`.padEnd(12));
319
+ if (cache.expired_entries > 0) cols.push(`${cache.expired_entries} expired`);
320
+ }
321
+ lines.push(` ${cols.join(' ').trimEnd()}`);
322
+ }
323
+
324
+ lines.push('');
325
+ lines.push(` Total: ${entryCount(stats.total_entries)}, ${formatBytes(stats.total_bytes)} under ${stats.config_dir}`);
326
+ lines.push(' Hits and misses are not recorded on disk, so there is no hit rate to report.');
327
+ lines.push('');
328
+ lines.push(' Caching is off unless --cache is passed. --no-cache (or NANSEN_NO_CACHE=1) bypasses it.');
329
+ lines.push(` Clear with: nansen cache clear [${CLEAR_TARGETS.join('|')}]`);
330
+
331
+ return lines.join('\n');
332
+ }
333
+
334
+ /** What a clear actually removed, cache by cache. */
335
+ export function formatCacheClear(result) {
336
+ const lines = result.removed.map(
337
+ cache => cache.entries > 0
338
+ ? `✓ Cleared ${entryCount(cache.entries)} (${formatBytes(cache.bytes)}) from the ${cache.label}\n ${cache.path}`
339
+ : `ℹ No entries to clear from the ${cache.label}\n ${cache.path}`
340
+ );
341
+ if (result.removed.length > 1) {
342
+ lines.push(` Total: ${entryCount(result.total_entries)}, ${formatBytes(result.total_bytes)}`);
343
+ }
344
+ return lines.join('\n');
345
+ }