nansen-cli 2.3.0 → 2.5.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 (80) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/README.md +61 -38
  3. package/docs/auth.md +56 -0
  4. package/docs/browser-login.md +101 -7
  5. package/docs/error-codes.md +251 -0
  6. package/package.json +10 -4
  7. package/skills/nansen-agent-guide/SKILL.md +20 -4
  8. package/skills/nansen-alerts-webhook-listener/SKILL.md +17 -14
  9. package/skills/nansen-dca-tracker/SKILL.md +1 -1
  10. package/skills/nansen-defi-positions/SKILL.md +1 -1
  11. package/skills/nansen-exit-signals/SKILL.md +2 -2
  12. package/skills/nansen-fund-tracker/SKILL.md +1 -1
  13. package/skills/nansen-general-search/SKILL.md +1 -1
  14. package/skills/nansen-holder-analysis/SKILL.md +2 -2
  15. package/skills/nansen-limit-orders/SKILL.md +9 -1
  16. package/skills/nansen-mpp-payment/SKILL.md +2 -2
  17. package/skills/nansen-perp-screener/SKILL.md +1 -1
  18. package/skills/nansen-perp-trader-profile/SKILL.md +1 -1
  19. package/skills/nansen-polymarket-deep-dive/SKILL.md +1 -1
  20. package/skills/nansen-polymarket-insider-scan/SKILL.md +1 -1
  21. package/skills/nansen-polymarket-trader-profile/SKILL.md +1 -1
  22. package/skills/nansen-portfolio-tracker/SKILL.md +1 -1
  23. package/skills/nansen-prediction-markets/SKILL.md +1 -1
  24. package/skills/nansen-sm-cross-chain-flows/SKILL.md +1 -1
  25. package/skills/nansen-smart-alerts/SKILL.md +5 -2
  26. package/skills/nansen-smart-money-alpha/SKILL.md +1 -1
  27. package/skills/nansen-smart-money-tracker/SKILL.md +8 -7
  28. package/skills/nansen-smart-money-trend/SKILL.md +1 -1
  29. package/skills/nansen-token-research/SKILL.md +1 -1
  30. package/skills/nansen-token-screener/SKILL.md +1 -1
  31. package/skills/nansen-token-transfer-analysis/SKILL.md +1 -1
  32. package/skills/nansen-trading/SKILL.md +23 -2
  33. package/skills/nansen-wallet-batch/SKILL.md +1 -1
  34. package/skills/nansen-wallet-clustering/SKILL.md +1 -1
  35. package/skills/nansen-wallet-deep-dive/SKILL.md +1 -1
  36. package/skills/nansen-wallet-keychain-migration/SKILL.md +1 -1
  37. package/skills/nansen-wallet-manager/SKILL.md +11 -5
  38. package/skills/nansen-wallet-profiler/SKILL.md +1 -1
  39. package/skills/nansen-web-fetcher/SKILL.md +1 -1
  40. package/skills/nansen-web-searcher/SKILL.md +1 -1
  41. package/src/api-endpoints.json +1605 -0
  42. package/src/api.js +282 -124
  43. package/src/auth-credentials.js +1 -0
  44. package/src/auth-key-input.js +57 -9
  45. package/src/auth-state.js +2 -2
  46. package/src/auth-store-native.js +6 -1
  47. package/src/auth-store-worker.js +1 -1
  48. package/src/auth-store.js +9 -4
  49. package/src/auto-paginate.js +25 -7
  50. package/src/bridge.js +19 -10
  51. package/src/cache-inspect.js +16 -6
  52. package/src/cli.js +272 -114
  53. package/src/commands/agent.js +2 -3
  54. package/src/commands/alerts.js +365 -18
  55. package/src/commands/completion.js +4 -1
  56. package/src/commands/feedback.js +98 -37
  57. package/src/commands/mcp.js +1 -1
  58. package/src/commands/research.js +14 -37
  59. package/src/cost-cache.js +33 -7
  60. package/src/doctor.js +14 -5
  61. package/src/ens.js +14 -5
  62. package/src/error-codes.js +228 -0
  63. package/src/execute-guard.js +8 -3
  64. package/src/input-validation.js +555 -0
  65. package/src/limit-order.js +127 -54
  66. package/src/perp.js +358 -35
  67. package/src/privy.js +90 -15
  68. package/src/query-options.js +47 -8
  69. package/src/response-cache-files.js +65 -0
  70. package/src/response-meta.js +8 -2
  71. package/src/rpc-urls.js +3 -1
  72. package/src/schema.json +1254 -156
  73. package/src/solana-tx.js +4 -0
  74. package/src/telemetry-flags.js +75 -0
  75. package/src/trade-validation.js +167 -8
  76. package/src/trading.js +243 -20
  77. package/src/transfer.js +79 -12
  78. package/src/update-check.js +32 -5
  79. package/src/wallet.js +246 -69
  80. package/src/walletconnect-x402.js +27 -9
@@ -6,12 +6,17 @@ function inputError(message, code) {
6
6
  return new CommandError(message, code, { error: code, message });
7
7
  }
8
8
 
9
- // Explicit stdin input keeps secrets out of command arguments and shell history.
10
- export async function readApiKeyInput(input, isTTY = input.isTTY, { timeoutMs = 30_000 } = {}) {
11
- if (isTTY) throw inputError('Pipe an API key or redirect a key file into --api-key-stdin. For a hidden terminal prompt, use nansen login --human.', 'NOT_A_PIPE');
9
+ /**
10
+ * Read a single secret from a pipe or redirected file. Shared by the API key
11
+ * (`--api-key-stdin`) and the alert webhook signing secret
12
+ * (`--webhook-secret-stdin`). `errors` maps each failure to the
13
+ * CommandError to throw; none of them may quote the input.
14
+ */
15
+ async function readSecretBytes(input, isTTY, { timeoutMs, maxBytes, errors }) {
16
+ if (isTTY) throw errors.notAPipe();
12
17
  const chunks = [];
13
18
  let size = 0;
14
- const timeoutError = inputError('Timed out reading the API key from stdin. Close the pipe after writing a single key, or redirect a key file.', 'API_KEY_INPUT_TIMEOUT');
19
+ const timeoutError = errors.timeout();
15
20
  let timer;
16
21
  let iterator;
17
22
  let exhausted = false;
@@ -23,12 +28,12 @@ export async function readApiKeyInput(input, isTTY = input.isTTY, { timeoutMs =
23
28
  if (done) { exhausted = true; break; }
24
29
  const bytes = Buffer.isBuffer(value) ? value : Buffer.from(value);
25
30
  size += bytes.length;
26
- if (size > MAX_KEY_BYTES) break;
31
+ if (size > maxBytes) break;
27
32
  chunks.push(bytes);
28
33
  }
29
34
  } catch (error) {
30
35
  if (error === timeoutError) throw timeoutError;
31
- throw inputError('Could not read the API key from stdin. Check the input and try again.', 'API_KEY_INPUT_FAILED');
36
+ throw errors.failed();
32
37
  } finally {
33
38
  clearTimeout(timer);
34
39
  try { input.destroy?.(); } catch { /* Never expose input cleanup errors. */ }
@@ -38,9 +43,52 @@ export async function readApiKeyInput(input, isTTY = input.isTTY, { timeoutMs =
38
43
  try { Promise.resolve(iterator?.return?.()).catch(() => {}); } catch { /* Preserve the sanitized input error. */ }
39
44
  }
40
45
  }
41
- if (size > MAX_KEY_BYTES) throw inputError('API key input exceeds 4096 bytes. Provide a single API key.', 'INVALID_PARAMS');
42
- const key = Buffer.concat(chunks).toString('utf8').trim();
46
+ if (size > maxBytes) throw errors.tooLarge();
47
+ return Buffer.concat(chunks).toString('utf8');
48
+ }
49
+
50
+ export function hasControlChars(value) {
51
+ return /�/u.test(value) || [...value].some(char => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127);
52
+ }
53
+
54
+ // Explicit stdin input keeps secrets out of command arguments and shell history.
55
+ export async function readApiKeyInput(input, isTTY = input.isTTY, { timeoutMs = 30_000 } = {}) {
56
+ const raw = await readSecretBytes(input, isTTY, {
57
+ timeoutMs,
58
+ maxBytes: MAX_KEY_BYTES,
59
+ errors: {
60
+ notAPipe: () => inputError('Pipe an API key or redirect a key file into --api-key-stdin. For a hidden terminal prompt, use nansen login --human.', 'NOT_A_PIPE'),
61
+ timeout: () => inputError('Timed out reading the API key from stdin. Close the pipe after writing a single key, or redirect a key file.', 'API_KEY_INPUT_TIMEOUT'),
62
+ failed: () => inputError('Could not read the API key from stdin. Check the input and try again.', 'API_KEY_INPUT_FAILED'),
63
+ tooLarge: () => inputError('API key input exceeds 4096 bytes. Provide a single API key.', 'INVALID_PARAMS'),
64
+ },
65
+ });
66
+ const key = raw.trim();
43
67
  if (!key) throw inputError('No API key received on stdin. Pipe a single key or redirect a key file.', 'API_KEY_REQUIRED');
44
- if (/\s|\ufffd/u.test(key) || [...key].some(char => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127)) throw inputError('API key input must contain a single key without whitespace or control characters.', 'INVALID_PARAMS');
68
+ if (/\s/u.test(key) || hasControlChars(key)) throw inputError('API key input must contain a single key without whitespace or control characters.', 'INVALID_PARAMS');
45
69
  return key;
46
70
  }
71
+
72
+ /**
73
+ * Read an alert webhook signing secret from stdin (`--webhook-secret-stdin`).
74
+ * Surrounding whitespace (such as the newline `echo` adds) is removed, so the
75
+ * secret matches what a listener reads from a trimmed env var or file. Inner
76
+ * spaces are kept; line breaks and other control characters are rejected
77
+ * because they mean more than one value was piped.
78
+ */
79
+ export async function readWebhookSecretInput(input, isTTY = input?.isTTY, { timeoutMs = 30_000 } = {}) {
80
+ const raw = await readSecretBytes(input, isTTY, {
81
+ timeoutMs,
82
+ maxBytes: MAX_KEY_BYTES,
83
+ errors: {
84
+ notAPipe: () => inputError('--webhook-secret-stdin reads from a pipe or redirected file, not a terminal. Example: nansen alerts create ... --webhook-secret-stdin < secret.txt, or set NANSEN_WEBHOOK_SECRET.', 'NOT_A_PIPE'),
85
+ timeout: () => inputError('Timed out reading the webhook secret from stdin. Close the pipe after writing the secret, or redirect a file.', 'INVALID_PARAMS'),
86
+ failed: () => inputError('Could not read the webhook secret from stdin. Check the input and try again.', 'INVALID_PARAMS'),
87
+ tooLarge: () => inputError('Webhook secret input exceeds 4096 bytes. Provide a single secret.', 'INVALID_PARAMS'),
88
+ },
89
+ });
90
+ const secret = raw.trim();
91
+ if (!secret) throw inputError('No webhook secret received on stdin. Pipe the secret or redirect a file that contains it.', 'MISSING_PARAM');
92
+ if (hasControlChars(secret)) throw inputError('Webhook secret input must be a single line without control characters.', 'INVALID_PARAMS');
93
+ return secret;
94
+ }
package/src/auth-state.js CHANGED
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import { setTimeout as delay } from 'node:timers/promises';
5
- import { AuthError, authDirectory, validAuthPointer } from './auth-credentials.js';
5
+ import { AuthError, authDirectory, validAuthPointer, ENV_API_KEY_GUIDANCE } from './auth-credentials.js';
6
6
  import { createAuthStore } from './auth-store.js';
7
7
  import { refreshSession, retireSession, validateSession } from './auth-device.js';
8
8
  import { openLocalFile, readLocalFile } from './local-file.js';
@@ -78,7 +78,7 @@ async function waitTurn(previous, signal) {
78
78
  }
79
79
  async function loadLocks() {
80
80
  try { return (await import('fs-native-extensions')).default; }
81
- catch { throw new AuthError('AUTH_LOCK_UNAVAILABLE', 'Native authentication locking is unavailable. Reinstall nansen-cli with optional dependencies; if they are installed, this platform may lack a compatible fs-native-extensions prebuild. Legacy key setup and logout require this binding. Environment API keys still work. For offline saved-key removal, stop every CLI/auth process, then follow docs/browser-login.md#offline-recovery-without-native-locking. Do not delete auth journals or wallet files.'); }
81
+ catch { throw new AuthError('AUTH_LOCK_UNAVAILABLE', `Native authentication locking is unavailable. ${ENV_API_KEY_GUIDANCE} Saved login and logout require this binding. Reinstall nansen-cli with optional dependencies; if they are installed, this platform may lack a compatible fs-native-extensions prebuild. For offline saved-key removal, stop every CLI/auth process, then follow docs/browser-login.md#offline-recovery-without-native-locking. Do not delete auth journals or wallet files.`); }
82
82
  }
83
83
  export function createAuthState({ directory = authDirectory(), store = createAuthStore({ directory }), retire = retireSession, refresh = refreshSession, now = Date.now, barrier = async () => {}, locks = loadLocks, waitMs = 15000, operationMs = 60000 } = {}) {
84
84
  let operationSignal;
@@ -16,5 +16,10 @@ try {
16
16
  else if (operation === 'delete') value = entry.deleteCredential();
17
17
  else throw new Error();
18
18
  parentPort.postMessage({ value });
19
- } catch { parentPort.postMessage({ error: 'STORE_UNAVAILABLE' }); }
19
+ } catch (error) {
20
+ // The binding exposes GenericFailure for both cases. Recognize only the
21
+ // upstream Secret Service refusal; never forward native messages or secrets.
22
+ const locked = process.platform === 'linux' && /Secret Service: unlock prompt was dismissed/.test(error?.message || '');
23
+ parentPort.postMessage({ error: locked ? 'STORE_LOCKED' : 'STORE_UNAVAILABLE' });
24
+ }
20
25
  }
@@ -45,7 +45,7 @@ function receive(line) {
45
45
  worker.on('error', stop);
46
46
  worker.on('exit', code => {
47
47
  // No response or lock release until the executor can no longer write.
48
- if (code !== 0 || !result || (result.error && result.error !== 'BINDING_MISSING')) return stop();
48
+ if (code !== 0 || !result || (result.error && !['BINDING_MISSING', 'STORE_LOCKED', 'STORE_UNAVAILABLE'].includes(result.error))) return stop();
49
49
  process.stdout.write(JSON.stringify(result) + '\n', () => {
50
50
  clearTimeout(timer);
51
51
  fs.closeSync(fd);
package/src/auth-store.js CHANGED
@@ -2,12 +2,12 @@ import { spawn } from 'node:child_process';
2
2
  import { randomBytes, createHash } from 'node:crypto';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import path from 'node:path';
5
- import { AuthError, authDirectory } from './auth-credentials.js';
5
+ import { AuthError, authDirectory, ENV_API_KEY_GUIDANCE } from './auth-credentials.js';
6
6
 
7
7
  export const CHUNK_BYTES = 2048;
8
8
  export const MAX_BUNDLE_BYTES = 16384;
9
9
  const digest = bytes => createHash('sha256').update(bytes).digest('hex');
10
- const unavailable = () => new AuthError('AUTH_STORE_UNAVAILABLE', 'Secure credential storage is unavailable or locked. Unlock your OS credential store and retry nansen login. No file fallback is used.');
10
+ const unavailable = () => new AuthError('AUTH_STORE_UNAVAILABLE', `Secure credential storage is unavailable or locked. ${ENV_API_KEY_GUIDANCE} To use browser login, enable and unlock your OS credential store, then retry nansen login from a supported terminal. On Linux, check the user D-Bus session, Secret Service provider and default collection; installing the native binding alone does not start or unlock a service. See docs/browser-login.md#linux-secret-service-setup. No file fallback is used.`);
11
11
  export function nativeStoreOperation(operation, account, bytes, { directory = authDirectory(), signal } = {}) {
12
12
  signal?.throwIfAborted();
13
13
  return new Promise((resolve, reject) => {
@@ -47,7 +47,7 @@ export function nativeStoreOperation(operation, account, bytes, { directory = au
47
47
  // The child already holds execution/cleanup exclusion. Keep the
48
48
  // pipe open as a parent-lifetime signal; never send secrets early.
49
49
  child.stdin.write(JSON.stringify({ operation, account, ...(bytes && { data: Buffer.from(bytes).toString('base64') }) }) + '\n');
50
- } else if (ready && !result && (Object.hasOwn(message, 'value') || message.error === 'BINDING_MISSING')) result = message;
50
+ } else if (ready && !result && (Object.hasOwn(message, 'value') || ['BINDING_MISSING', 'STORE_LOCKED', 'STORE_UNAVAILABLE'].includes(message.error))) result = message;
51
51
  else throw new Error();
52
52
  } catch { stop(); }
53
53
  }
@@ -62,9 +62,14 @@ export function nativeStoreOperation(operation, account, bytes, { directory = au
62
62
  try {
63
63
  if (failed || code !== 0 || !ready || !result || output) throw new Error();
64
64
  if (result.error === 'BINDING_MISSING') {
65
- reject(new AuthError('AUTH_STORE_UNAVAILABLE', 'The native credential-store binding could not load. Reinstall nansen-cli with optional dependencies enabled on a supported OS and architecture. See nansen doctor --offline and the browser-login platform guide.'));
65
+ reject(new AuthError('AUTH_STORE_UNAVAILABLE', `The native credential-store binding could not load. ${ENV_API_KEY_GUIDANCE} For saved browser login, reinstall nansen-cli with optional dependencies enabled on a supported OS and architecture. See docs/browser-login.md#preview-platform-scope.`));
66
66
  return;
67
67
  }
68
+ if (result.error === 'STORE_LOCKED') {
69
+ reject(new AuthError('AUTH_STORE_UNAVAILABLE', `The Linux Secret Service unlock prompt was dismissed or could not run in this terminal. Unlock the default collection using your provider's tools in the same user D-Bus session, then retry. Starting the service alone does not unlock it. See docs/browser-login.md#linux-secret-service-setup. ${ENV_API_KEY_GUIDANCE}`));
70
+ return;
71
+ }
72
+ if (result.error) { reject(unavailable()); return; }
68
73
  resolve(operation === 'get' && result.value !== null ? Buffer.from(result.value, 'base64') : result.value);
69
74
  } catch { reject(unavailable()); }
70
75
  });
@@ -213,6 +213,16 @@ export async function collectPages(fetchPage, pagination, { maxPages = DEFAULT_M
213
213
  return merged;
214
214
  }
215
215
 
216
+ /**
217
+ * The merged result reuses page 1's envelope, so its `_meta.fromCache` and
218
+ * `cacheAge` describe page 1 only. Keep them only when every page was cached.
219
+ */
220
+ function withMergedCacheMarker(result, pages) {
221
+ if (result?._meta?.fromCache !== true || pages.every(page => page.cached)) return result;
222
+ const { fromCache: _fromCache, cacheAge: _cacheAge, ...meta } = result._meta;
223
+ return { ...result, _meta: meta };
224
+ }
225
+
216
226
  /**
217
227
  * Make `api.request` traverse pages for list bodies. Returns the same
218
228
  * instance. NansenAPI never calls request() recursively (x402 retries use
@@ -235,19 +245,26 @@ export function enableAutoPagination(api, opts = {}) {
235
245
  api.paginatedEndpoint = null;
236
246
  const pageMetadata = [];
237
247
  const recordPageMetadata = (meta, cached = false) => {
238
- pageMetadata.push({ cached, meta: cached ? null : meta });
248
+ pageMetadata.push({ cached, meta });
239
249
  };
240
250
  try {
241
- return await collectPages(async pagination => {
251
+ const result = await collectPages(async pagination => {
242
252
  const previousMeta = api.lastResponseMeta;
253
+ let requestMetadata;
243
254
  try {
244
- const pageResult = await request(endpoint, { ...body, pagination }, options);
255
+ const pageResult = await request(endpoint, { ...body, pagination }, {
256
+ ...options,
257
+ onResponseMeta(meta, cached) {
258
+ requestMetadata = { meta, cached };
259
+ options.onResponseMeta?.(meta, cached);
260
+ },
261
+ });
245
262
  // The payload belongs to this exact request, unlike the instance's
246
263
  // last-* fields which concurrent non-list calls can overwrite.
247
- const cached = pageResult?._meta?.fromCache === true
248
- || (api.responseMetadataOnPayload !== true && api.servedFromCache === true);
264
+ const cached = requestMetadata?.cached ?? (pageResult?._meta?.fromCache === true
265
+ || (api.responseMetadataOnPayload !== true && api.servedFromCache === true));
249
266
  const payloadMeta = pageResult?.[RESPONSE_META];
250
- const meta = payloadMeta ?? (
267
+ const meta = requestMetadata ? requestMetadata.meta : payloadMeta ?? (
251
268
  api.responseMetadataOnPayload === true ? null : api.lastResponseMeta
252
269
  );
253
270
  recordPageMetadata(meta, cached);
@@ -265,12 +282,13 @@ export function enableAutoPagination(api, opts = {}) {
265
282
  // A transport failure may leave the prior page's metadata in place;
266
283
  // count the attempt, but only use shared state when the error itself
267
284
  // carries no metadata and this request demonstrably replaced it.
268
- recordPageMetadata(hasErrorMeta
285
+ recordPageMetadata(requestMetadata ? requestMetadata.meta : hasErrorMeta
269
286
  ? errorMeta
270
287
  : (api.lastResponseMeta === previousMeta ? null : api.lastResponseMeta));
271
288
  throw error;
272
289
  }
273
290
  }, body.pagination, opts);
291
+ return withMergedCacheMarker(result, pageMetadata);
274
292
  } finally {
275
293
  api.paginatedResponseMeta = aggregatePaginatedResponseMeta(pageMetadata);
276
294
  api.paginatedEndpoint = endpoint;
package/src/bridge.js CHANGED
@@ -1918,13 +1918,15 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1918
1918
  log(` Type: ${execution_type}`);
1919
1919
  log(` Steps: ${steps.length}`);
1920
1920
 
1921
- // Dry-run preflight needs only the public address persisted alongside the
1922
- // quote. Prefer it before touching local wallet configuration; legacy
1923
- // quotes without the field retain the previous wallet-resolution path.
1924
- // A real execution always resolves the live signer independently and
1925
- // binds it to the quote before any credentials are loaded.
1921
+ // Dry-run preflight normally needs only the public address persisted with
1922
+ // the quote. Privy Hyperliquid quotes are the exception: resolve the live
1923
+ // signer so its wallet ID can be bound before even showing a preview.
1924
+ // Real execution always resolves the live signer independently and binds
1925
+ // it to the quote before any credentials are loaded.
1926
1926
  const quotedWalletAddress = validateQuotedWalletAddress(quoteId, quoteData.walletAddress);
1927
- const signer = guard.dryRun && quotedWalletAddress
1927
+ const requiresPrivyBinding = execution_type === 'hyperliquid_signature'
1928
+ && quoteData.walletProvider === 'privy';
1929
+ const signer = guard.dryRun && quotedWalletAddress && !requiresPrivyBinding
1928
1930
  ? null
1929
1931
  : resolveWalletAddress(walletName);
1930
1932
  const signerAddress = signer?.address || quotedWalletAddress;
@@ -1947,6 +1949,15 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1947
1949
  );
1948
1950
  }
1949
1951
 
1952
+ let privyBinding = null;
1953
+ if (execution_type === 'hyperliquid_signature' && signer?.provider === 'privy') {
1954
+ const { PrivyClient, assertPrivyWalletAddress } = await import('./privy.js');
1955
+ const client = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
1956
+ const walletId = signer.privyWalletIds?.evm;
1957
+ await assertPrivyWalletAddress(client, walletId, signer.address, 'evm');
1958
+ privyBinding = { client, walletId };
1959
+ }
1960
+
1950
1961
  // Re-screen the signer and any distinct recipient immediately before
1951
1962
  // signing. Quotes live up to an hour, and the EVM leg broadcasts directly.
1952
1963
  const screenAddresses = recipient
@@ -2106,14 +2117,12 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
2106
2117
  }
2107
2118
  } else if (execution_type === 'hyperliquid_signature') {
2108
2119
  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
2120
  for (const [index, step] of steps.entries()) {
2112
2121
  await processSignatureStepPrivy(step, {
2113
- privyClient,
2122
+ privyClient: privyBinding.client,
2114
2123
  // `signer` above — the same resolution that was screened and
2115
2124
  // matched against the quote, rather than resolving a second time.
2116
- walletId: signer.privyWalletIds?.evm,
2125
+ walletId: privyBinding.walletId,
2117
2126
  log,
2118
2127
  apiInstance,
2119
2128
  onBroadcast,
@@ -12,8 +12,9 @@
12
12
  * and they are not printed either.
13
13
  *
14
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
15
+ * `.json` entries directly inside the response cache directory (plus temp
16
+ * files that a killed write left behind, once they are 10 minutes old), and
17
+ * the two named files. Directories and symlinks are skipped rather than followed, so a
17
18
  * clear cannot reach outside the cache it was pointed at. Everything else under
18
19
  * ~/.nansen (config.json, wallets/, quotes/, telemetry-id, saved auth) is never
19
20
  * read or deleted by the inspector. CLI startup loads config separately.
@@ -22,13 +23,13 @@
22
23
  import fs from 'fs';
23
24
  import path from 'path';
24
25
  import { openLocalFile } from './local-file.js';
26
+ import { RESPONSE_ENTRY, RESPONSE_TEMP, isStaleTemp } from './response-cache-files.js';
25
27
 
26
28
  import { getCacheDir, getConfigDir, DEFAULT_CACHE_TTL, NansenError, ErrorCode } from './api.js';
27
29
  import { getCostMapFile, COST_MAP_TTL_MS } from './cost-cache.js';
28
30
  import { getUpdateCheckFile, UPDATE_CHECK_TTL_MS } from './update-check.js';
29
31
 
30
32
  const SECOND = 1000;
31
- const RESPONSE_ENTRY = /^[0-9a-f]{64}\.json$/;
32
33
 
33
34
  /** Cache names, in report order. */
34
35
  export const CACHE_NAMES = ['responses', 'cost-map', 'update-check'];
@@ -106,7 +107,7 @@ function readTimestamp(file, field) {
106
107
  }
107
108
  }
108
109
 
109
- function listDirEntries(dir, { readMetadata = false } = {}) {
110
+ function listDirEntries(dir, { readMetadata = false, includeStaleTemps = false } = {}) {
110
111
  let names;
111
112
  try {
112
113
  const dirStat = fs.lstatSync(dir);
@@ -123,16 +124,25 @@ function listDirEntries(dir, { readMetadata = false } = {}) {
123
124
  throw fsError('list', dir, error);
124
125
  }
125
126
  const entries = [];
127
+ const now = Date.now();
126
128
  for (const name of names) {
127
129
  // `name` comes from this directory's own listing, not from a caller. The
128
130
  // strict digest shape both identifies files written by api.js and prevents
129
131
  // path separators or traversal segments from reaching path.join(). The
130
132
  // lstat below then rejects a final-component symlink before any read/delete.
131
- if (!RESPONSE_ENTRY.test(name)) continue;
133
+ // A temp file is a write that never finished renaming onto its entry.
134
+ // Only stale ones are listed (for clearing), so a write in progress is
135
+ // never deleted, and they have no timestamp metadata to read.
136
+ const isTemp = includeStaleTemps && RESPONSE_TEMP.test(name);
137
+ if (!isTemp && !RESPONSE_ENTRY.test(name)) continue;
132
138
  const file = path.join(dir, name);
133
139
  try {
134
140
  const stat = fs.lstatSync(file);
135
141
  if (!stat.isFile()) continue;
142
+ if (isTemp) {
143
+ if (isStaleTemp(name, stat, now)) entries.push({ file, bytes: stat.size });
144
+ continue;
145
+ }
136
146
  const metadata = readMetadata ? readTimestamp(file, 'timestamp') : {};
137
147
  if (metadata.raced) continue;
138
148
  entries.push({ file, bytes: stat.size, ...metadata });
@@ -256,7 +266,7 @@ export function clearCaches(target) {
256
266
  if (!wanted.includes(ns.name)) continue;
257
267
  let entries = 0;
258
268
  let bytes = 0;
259
- for (const entry of listEntries(ns, { readMetadata: false })) {
269
+ for (const entry of listEntries(ns, { readMetadata: false, includeStaleTemps: true })) {
260
270
  try {
261
271
  fs.unlinkSync(entry.file);
262
272
  } catch (error) {