nansen-cli 2.4.0 → 2.6.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.
@@ -68,6 +68,8 @@ nansen trade execute --quote <quote-id> --yes # skip the confirmation prom
68
68
 
69
69
  **Agents and CI are unaffected:** when stdin is *not* a terminal (a pipe, a CI job, an agent shell) the command proceeds without prompting, exactly as before. `--yes` is accepted there and is simply a no-op, so it is safe to always pass it. The same flags and rules apply to `nansen bridge execute`.
70
70
 
71
+ **Operator stop point (`NANSEN_REQUIRE_CONFIRM=1`).** If the user has set `NANSEN_REQUIRE_CONFIRM=1`, a non-terminal run without `--yes` fails with `CONFIRMATION_REQUIRED` (exit 1) before any request or signature. That means the user wants to approve each broadcast: show them the `--dry-run` plan, and only re-run with `--yes` after they say go. Do not unset the variable to get around it.
72
+
71
73
  ### Exit codes (`trade execute`, `bridge execute`)
72
74
 
73
75
  | Code | Meaning |
@@ -121,6 +123,8 @@ nansen trade limit-order update --order <order-id> --trigger-price 85
121
123
 
122
124
  `--slippage-bps` is basis points (`300` = 3%, `100` = 1%); omit for auto.
123
125
 
126
+ `create` and `cancel` take the same `--dry-run` and `--yes` as `trade execute`. `--dry-run` prints the order (or cancellation) plan from the arguments and the wallet's public address and exits 0, with no API request, signature or submission; a cancel preview does not request the one-time cancellation transaction. In an interactive terminal they ask before signing; agents and CI run unprompted, and `--yes` is a no-op there.
127
+
124
128
  ## Agent pattern
125
129
 
126
130
  ```bash
@@ -187,7 +191,7 @@ If the user says "$20 worth of X", use `--amount-unit usd` directly — no manua
187
191
  | `--quote-index` | Pin a specific quote by index (0-based) when multiple quotes were returned |
188
192
  | `--no-simulate` | Skip pre-broadcast simulation |
189
193
  | `--dry-run` | Validate and print what would be sent, then stop. Nothing is signed or broadcast |
190
- | `--yes`, `-y` | Skip the confirmation prompt (same as `NANSEN_YES=1`); no-op when stdin is not a terminal |
194
+ | `--yes`, `-y` | Skip the confirmation prompt (same as `NANSEN_YES=1`); no-op when stdin is not a terminal, unless `NANSEN_REQUIRE_CONFIRM=1` is set, which makes it required there |
191
195
 
192
196
  ### `trade bridge-status` flags
193
197
 
@@ -203,7 +207,8 @@ If the user says "$20 worth of X", use `--amount-unit usd` directly — no manua
203
207
  |-----|---------|
204
208
  | `NANSEN_WALLET_PASSWORD` | **Required for `trade execute`.** Wallet encryption password — persisted in `~/.nansen/.env`. Source before executing: `source ~/.nansen/.env && nansen trade execute ...` |
205
209
  | `NANSEN_API_KEY` | API key (also set via explicit `nansen login --human`; browser sessions are not wallet or RPC keys) |
206
- | `NANSEN_YES` | Set to `1` to skip the `execute` confirmation prompt, like `--yes` |
210
+ | `NANSEN_YES` | Set to `1` to skip the confirmation prompt of `trade execute`, `bridge execute`, `trade limit-order create`/`cancel` and `perp order`/`close`/`cancel`/`leverage`, like `--yes` |
211
+ | `NANSEN_REQUIRE_CONFIRM` | Set to `1` to make those same commands fail with `CONFIRMATION_REQUIRED`, before any request or signature, when stdin is not a terminal and neither `--yes` nor `NANSEN_YES=1` is given. `--dry-run` still works. Opt-in; unset keeps today's behaviour |
207
212
 
208
213
  > **Agents:** Never hold a wallet password only in session memory. If `NANSEN_WALLET_PASSWORD` is not in `~/.nansen/.env`, follow the setup flow in the nansen-wallet-manager skill Password Policy to generate and persist one before proceeding.
209
214
 
@@ -220,16 +225,33 @@ Use `nansen perp` for Hyperliquid perpetual trading. Uses the same wallet and `N
220
225
 
221
226
  Subcommands: `order`, `cancel`, `close`, `leverage`, `positions`, `orders`, `account`, `meta`.
222
227
 
223
- The asset is selected with `--coin` (e.g. `BTC`, `ETH`); `--symbol` is accepted as an alias. List tradable assets and their max leverage with `nansen perp meta` (use `--filter <text>` or `--all` to see beyond the first 20).
228
+ The asset is selected with `--symbol` (e.g. `BTC`, `ETH`); `--coin` is accepted as an alias. List tradable assets and their max leverage with `nansen perp meta` (use `--filter <text>` or `--all` to see beyond the first 20).
229
+
230
+ ## Preview and confirm (`--dry-run`, `--yes`)
231
+
232
+ `order`, `close`, `cancel` and `leverage` have no quote step, so a typo in `--size` or `--price` would otherwise go straight to the exchange. Preview first:
233
+
234
+ ```bash
235
+ nansen perp order --symbol ETH --side buy --size 0.1 --price 1600 --dry-run # preview only, nothing is signed
236
+ nansen perp order --symbol ETH --side buy --size 0.1 --price 1600 --yes # skip the confirmation prompt
237
+ ```
238
+
239
+ **`--dry-run`** runs the normal validation and read-only lookups (asset metadata, builder fee, open position, compliance screen), prints the plan (coin, side, rounded size, price and type, take-profit/stop-loss, estimated notional, leverage, builder fee) and exits 0. Nothing is signed or sent to Hyperliquid, no wallet password is needed, and the one-time builder-fee approval is not submitted. `close` also shows the worst fill price after slippage and the open position, `cancel` shows the open order it would cancel, and `leverage` shows the new setting next to the asset maximum.
240
+
241
+ **Exception: `close --dry-run` exits 1 with `NO_OPEN_POSITION` when the wallet has no open position in that coin.** That is a definite "nothing to close" answer, not a crash. If the position was opened moments ago, the positions data may not show it yet: retry after a few seconds. A real `close` skips this check and lets Hyperliquid decide; with a prompt, its plan shows a warning instead.
242
+
243
+ **Confirmation.** When stdin is an interactive terminal, these four commands print the plan and ask, for example, `Submit this order to Hyperliquid? [y/N]` before signing. Answering anything but `y`/`yes` exits 1 with nothing signed (code `CONFIRMATION_DECLINED`). Pass `--yes` (`-y`), or set `NANSEN_YES=1`, to skip the question.
244
+
245
+ **When stdin is *not* a terminal** (agents, CI) the commands submit without prompting, exactly as before, and `--yes` is a no-op. **Exception:** if `NANSEN_REQUIRE_CONFIRM=1` is set, they fail with `CONFIRMATION_REQUIRED` (exit 1) before any request or signature unless `--yes` or `NANSEN_YES=1` is given; follow the operator stop point described above. These are the same rules as `trade execute` and `bridge execute`. `transfer` and `approve-builder-fee` are unchanged.
224
246
 
225
247
  ## Open a position
226
248
 
227
249
  ```bash
228
250
  # Limit long: 0.1 ETH at $1600
229
- nansen perp order --coin ETH --side buy --size 0.1 --price 1600 --type limit
251
+ nansen perp order --symbol ETH --side buy --size 0.1 --price 1600 --type limit
230
252
 
231
253
  # Market short with optional take-profit / stop-loss
232
- nansen perp order --coin BTC --side sell --size 0.001 --price 95000 --type market \
254
+ nansen perp order --symbol BTC --side sell --size 0.001 --price 95000 --type market \
233
255
  --take-profit 90000 --stop-loss 98000
234
256
  ```
235
257
 
@@ -239,22 +261,22 @@ nansen perp order --coin BTC --side sell --size 0.001 --price 95000 --type marke
239
261
  - `--type`: `limit` (default) or `market`. `--tif`: `Gtc` (default), `Ioc`, `Alo`.
240
262
  - `--slippage`: decimal in `[0,1]` for market orders (default `0.03` = 3%).
241
263
 
242
- On success the command prints the Hyperliquid order id (`oid`) and the fill (size @ avg price). A resting (unfilled) order also prints a ready-to-run `nansen perp cancel --coin <coin> --oid <oid>`. Attached take-profit/stop-loss legs are labelled and each print their own `oid`.
264
+ On success the command prints the Hyperliquid order id (`oid`) and the fill (size @ avg price). A resting (unfilled) order also prints a ready-to-run `nansen perp cancel --symbol <symbol> --oid <oid>`. Attached take-profit/stop-loss legs are labelled and each print their own `oid`.
243
265
 
244
266
  ## Close / cancel
245
267
 
246
268
  ```bash
247
269
  # Close: sell to close a long, buy to close a short (validated against your open position)
248
- nansen perp close --coin ETH --size 0.1 --price 1600 --side sell
270
+ nansen perp close --symbol ETH --size 0.1 --price 1600 --side sell
249
271
 
250
272
  # Cancel a resting order by id
251
- nansen perp cancel --coin ETH --oid 123456
273
+ nansen perp cancel --symbol ETH --oid 123456
252
274
  ```
253
275
 
254
276
  ## Leverage, transfers & account
255
277
 
256
278
  ```bash
257
- nansen perp leverage --coin ETH --leverage 5 --margin-type cross # or isolated
279
+ nansen perp leverage --symbol ETH --leverage 5 --margin-type cross # or isolated
258
280
  nansen perp transfer --direction spot-to-perp --amount 25 # or perp-to-spot
259
281
  nansen perp positions
260
282
  nansen perp account # account value, unrealized PnL, margin used, withdrawable, spot USDC
@@ -262,6 +284,8 @@ nansen perp account # account value, unrealized PnL, margin used, withdrawab
262
284
 
263
285
  `--leverage` must be a whole integer and is capped at the asset's maximum (see `perp meta`).
264
286
 
287
+ **Reading `perp positions`:** each line shows the leverage setting and margin mode before the liquidation price, e.g. `lev=1x cross liq=1.37`. The liquidation price is Hyperliquid's own figure. On cross margin it depends on the whole account's equity (fees, funding, losses on other cross positions), so a 1x position can still have a liquidation price near the market. `liq=n/a` means the exchange reports none.
288
+
265
289
  **Spot vs Perps:** perp trading draws from the **Perps** balance, but USDC sent to a wallet via Hyperliquid's **Send** lands in **Spot** (and shows as `Spot USDC` in `perp account`). Move it across with `perp transfer --direction spot-to-perp --amount <usdc>` before trading. (Deposits via the bridge land in Perps directly.)
266
290
 
267
291
  ## Source
@@ -90,7 +90,9 @@ After creation, the CLI automatically saves the password:
90
90
  - **OS keychain** (macOS Keychain, Linux secret-tool, Windows Credential Manager) — secure, preferred
91
91
  - **~/.nansen/wallets/.credentials file** — insecure fallback when no keychain is available (e.g. containers, CI)
92
92
 
93
- **All future wallet operations retrieve the password automatically** — no env var or human input needed.
93
+ **Once the password is saved, future wallet operations retrieve it automatically** — no env var or human input needed (unless it could not be saved; see below).
94
+
95
+ If neither store can be written, `wallet create` still succeeds but prints `CRITICAL: Password could not be saved anywhere`. The password is then not persisted: keep `NANSEN_WALLET_PASSWORD` set for every later wallet command, or the wallet cannot be decrypted.
94
96
 
95
97
  If the `.credentials` file fallback is used, the CLI prints a warning on every operation. To migrate to secure storage later, run `nansen wallet secure`.
96
98
 
@@ -106,7 +108,7 @@ If the `.credentials` file fallback is used, the CLI prints a warning on every o
106
108
  - **NEVER generate a password yourself** — always ask the human user
107
109
  - **NEVER store the password** in files, memory, logs, or conversation history
108
110
  - **NEVER use `--human` flag** — that enables interactive prompts which agents cannot handle
109
- - After wallet creation, you do NOT need the password for future operations — the keychain handles it
111
+ - After wallet creation, you do NOT need the password for future operations if it was saved (keychain or `.credentials`). If create printed `CRITICAL: Password could not be saved anywhere`, keep `NANSEN_WALLET_PASSWORD` set
110
112
  - If you get a `PASSWORD_REQUIRED` error, ask the user to provide their password again
111
113
 
112
114
  ## Create
@@ -144,6 +146,9 @@ nansen wallet default <name>
144
146
  # Send native token (SOL, ETH) — password auto-resolved from keychain
145
147
  nansen wallet send --to <addr> --amount 1.5 --chain solana
146
148
 
149
+ # Send a token: USDC, USDT, or the token's contract/mint address
150
+ nansen wallet send --to <addr> --amount 25 --chain base --token USDC
151
+
147
152
  # Send entire balance
148
153
  nansen wallet send --to <addr> --chain evm --max
149
154
 
@@ -192,7 +197,8 @@ For detailed migration steps (from `~/.nansen/.env`, `.credentials`, or env-var-
192
197
  |------|---------|
193
198
  | `--to` | Recipient address |
194
199
  | `--amount` | Amount to send |
195
- | `--chain` | `evm` or `solana` |
200
+ | `--chain` | `evm` (Ethereum), `ethereum`, `base` or `solana` |
201
+ | `--token` | Token to send: `USDC`, `USDT`, or a contract/mint address (native if omitted) |
196
202
  | `--max` | Send entire balance |
197
203
  | `--dry-run` | Preview without broadcasting |
198
204
  | `--provider` | Wallet provider: `local` (default, encrypted on disk) or `privy` (server-side via Privy API) |
@@ -205,7 +211,7 @@ For detailed migration steps (from `~/.nansen/.env`, `.credentials`, or env-var-
205
211
 
206
212
  | Var | Purpose |
207
213
  |-----|---------|
208
- | `NANSEN_WALLET_PASSWORD` | Wallet encryption password — only needed for initial `wallet create`. After that, the OS keychain handles it. |
214
+ | `NANSEN_WALLET_PASSWORD` | Wallet encryption password — only needed for initial `wallet create` when the password is saved (keychain or `.credentials`). If it could not be saved, keep it set for every wallet command. |
209
215
  | `NANSEN_API_KEY` | API key (can also be saved via `nansen login --human`) |
210
216
  | `PRIVY_APP_ID` | Privy application ID (required for `--provider privy`) |
211
217
  | `PRIVY_APP_SECRET` | Privy application secret (required for `--provider privy`) |
@@ -39,4 +39,4 @@ Positional args and `--query` flags can be combined — all become queries.
39
39
 
40
40
  Returns `results[]` — one entry per query, each with `organic[]` (title, link, snippet, date) and optional `knowledge_graph`.
41
41
 
42
- **Note:** Some domains are excluded from results (paywalled/unfetchable sites like bloomberg.com, twitter.com). Use `nansen web fetch` to retrieve content from specific URLs.
42
+ **Note:** Some domains are excluded from results (paywalled/unfetchable sites like bloomberg.com, twitter.com).
package/src/api.js CHANGED
@@ -15,6 +15,7 @@ import { readResponseMeta, stringHeader } from './response-meta.js';
15
15
  import { trace, traceRequest, traceResponse, traceError, traceRetry, traceCacheHit } from './debug.js';
16
16
  import { appendPaymentRecord, newPaymentId, sanitizeRequestUrl } from './x402-audit.js';
17
17
  import { openLocalFile } from './local-file.js';
18
+ import { ENTRY_MAX_AGE_MS, isStaleTemp, pruneResponseCacheDir } from './response-cache-files.js';
18
19
 
19
20
  /**
20
21
  * Key for the credit/rate-limit metadata attached to a successful response.
@@ -423,9 +424,11 @@ function getCacheKey(endpoint, body, context = {}) {
423
424
  /**
424
425
  * Get cached response if valid
425
426
  */
426
- export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL, context = {}) {
427
+ export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL, context = {}, onHit = null) {
427
428
  const cacheKey = getCacheKey(endpoint, body, context);
428
429
  const cacheFile = path.join(CACHE_DIR, `${cacheKey}.json`);
430
+ // The sweep after a write keeps entries this process may still read.
431
+ if (Number.isFinite(ttlSeconds) && ttlSeconds > largestReadTtlSeconds) largestReadTtlSeconds = ttlSeconds;
429
432
 
430
433
  if (!fs.existsSync(cacheFile)) {
431
434
  return null;
@@ -458,6 +461,10 @@ export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL
458
461
  } else {
459
462
  result = { ...cached.data, _meta: meta };
460
463
  }
464
+ const warningMeta = typeof cached.warning === 'string' && cached.warning
465
+ ? { notices: { warning: cached.warning } } : null;
466
+ if (result !== null && typeof result === 'object' && warningMeta) result[RESPONSE_META] = warningMeta;
467
+ onHit?.(warningMeta);
461
468
  }
462
469
  } catch (error) {
463
470
  primaryError = error;
@@ -477,7 +484,7 @@ export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL
477
484
  /**
478
485
  * Save response to cache
479
486
  */
480
- export function setCachedResponse(endpoint, body, data, context = {}) {
487
+ export function setCachedResponse(endpoint, body, data, context = {}, responseMeta = data?.[RESPONSE_META]) {
481
488
  if (!fs.existsSync(CACHE_DIR)) {
482
489
  fs.mkdirSync(CACHE_DIR, { mode: 0o700, recursive: true });
483
490
  }
@@ -488,6 +495,7 @@ export function setCachedResponse(endpoint, body, data, context = {}) {
488
495
  const cached = {
489
496
  timestamp: Date.now(),
490
497
  endpoint,
498
+ warning: responseMeta?.notices?.warning,
491
499
  data
492
500
  };
493
501
 
@@ -522,22 +530,58 @@ export function setCachedResponse(endpoint, body, data, context = {}) {
522
530
  try { fs.unlinkSync(tempFile); } catch { /* rename may already have committed */ }
523
531
  if (primaryError) throw primaryError;
524
532
  if (closeError) throw closeError;
533
+ sweepResponseCache(cacheFile);
534
+ }
535
+
536
+ // Sweep old entries and abandoned temp files after the first successful write
537
+ // in a process, then at most once per RESPONSE_CACHE_SWEEP_INTERVAL_MS so a
538
+ // long-running process keeps sweeping. Best effort: the response is already
539
+ // cached and a failed sweep must not fail the request. Ages are measured
540
+ // against the mtime of the entry just written rather than Date.now(), so every
541
+ // file is judged by the same clock (a network filesystem may stamp its own
542
+ // time) and the new entry itself is never older than the window. Entries this
543
+ // process may still read with a longer TTL are kept.
544
+ const RESPONSE_CACHE_SWEEP_INTERVAL_MS = 60 * 60 * 1000;
545
+ let lastResponseCacheSweep;
546
+ let largestReadTtlSeconds = 0;
547
+ function sweepResponseCache(writtenFile) {
548
+ const now = Date.now();
549
+ if (lastResponseCacheSweep !== undefined && now - lastResponseCacheSweep < RESPONSE_CACHE_SWEEP_INTERVAL_MS) return;
550
+ lastResponseCacheSweep = now;
551
+ try {
552
+ const retentionMs = Math.max(ENTRY_MAX_AGE_MS, largestReadTtlSeconds * 1000);
553
+ pruneResponseCacheDir(CACHE_DIR, fs.lstatSync(writtenFile).mtimeMs, retentionMs);
554
+ } catch {
555
+ // The next process tries again.
556
+ }
525
557
  }
526
558
 
527
559
  /**
528
560
  * Clear all cached responses
529
561
  */
530
562
  export function clearCache() {
531
- if (fs.existsSync(CACHE_DIR)) {
532
- const files = fs.readdirSync(CACHE_DIR);
533
- for (const file of files) {
534
- if (file.endsWith('.json')) {
535
- fs.unlinkSync(path.join(CACHE_DIR, file));
563
+ // Like the sweep and `nansen cache clear`, never follow a symlinked cache
564
+ // directory: deletes stay inside the directory itself.
565
+ const dirStat = fs.lstatSync(CACHE_DIR, { throwIfNoEntry: false });
566
+ if (!dirStat?.isDirectory()) return 0;
567
+ const files = fs.readdirSync(CACHE_DIR);
568
+ const now = Date.now();
569
+ let removed = 0;
570
+ for (const file of files) {
571
+ const full = path.join(CACHE_DIR, file);
572
+ if (file.endsWith('.json')) {
573
+ fs.unlinkSync(full);
574
+ removed += 1;
575
+ } else {
576
+ // A temp file younger than this may belong to a write in progress.
577
+ const stat = fs.lstatSync(full, { throwIfNoEntry: false });
578
+ if (stat?.isFile() && isStaleTemp(file, stat, now)) {
579
+ fs.unlinkSync(full);
580
+ removed += 1;
536
581
  }
537
582
  }
538
- return files.length;
539
583
  }
540
- return 0;
584
+ return removed;
541
585
  }
542
586
 
543
587
  /**
@@ -1073,6 +1117,7 @@ export class NansenAPI {
1073
1117
  }
1074
1118
  const meta = readResponseMeta(paidResponse);
1075
1119
  this.lastResponseMeta = meta;
1120
+ options.onResponseMeta?.(meta, false);
1076
1121
  if (meta && data !== null && typeof data === 'object') data[RESPONSE_META] = meta;
1077
1122
  return data;
1078
1123
  }
@@ -1107,8 +1152,18 @@ export class NansenAPI {
1107
1152
 
1108
1153
  let cacheContext = credentialContext();
1109
1154
  if (useCache && cacheContext) {
1110
- const cached = getCachedResponse(endpoint, body, cacheTtl, cacheContext);
1111
- if (cached) {
1155
+ let hit = false;
1156
+ const cached = getCachedResponse(endpoint, body, cacheTtl, cacheContext, meta => {
1157
+ hit = true;
1158
+ options.onResponseMeta?.(meta, true);
1159
+ const warning = meta?.notices?.warning;
1160
+ if (warning) {
1161
+ const previous = this.lastResponseMeta;
1162
+ const combined = [...new Set([previous?.notices?.warning, warning].filter(Boolean))].join(', ');
1163
+ this.lastResponseMeta = { ...previous, notices: { ...previous?.notices, warning: combined } };
1164
+ }
1165
+ });
1166
+ if (hit) {
1112
1167
  this.servedFromCache = true;
1113
1168
  traceCacheHit({ method, url });
1114
1169
  return cached;
@@ -1211,10 +1266,13 @@ export class NansenAPI {
1211
1266
  lastError = error;
1212
1267
  continue;
1213
1268
  }
1269
+ options.onResponseMeta?.(meta, false);
1214
1270
  throw error;
1215
1271
  }
1216
1272
 
1217
1273
  if (!response.ok) {
1274
+ // A literal `null` body parses as JSON but has no fields to read.
1275
+ if (data == null) data = {};
1218
1276
  let message = data.message || data.error
1219
1277
  || (typeof data.detail === 'string' ? data.detail : data.detail?.message)
1220
1278
  || `API error: ${response.status}`;
@@ -1444,6 +1502,7 @@ export class NansenAPI {
1444
1502
  continue;
1445
1503
  }
1446
1504
 
1505
+ options.onResponseMeta?.(meta, false);
1447
1506
  throw lastError;
1448
1507
  }
1449
1508
 
@@ -1452,18 +1511,14 @@ export class NansenAPI {
1452
1511
  data._meta = { ...(data._meta || {}), retriedAttempts: attempt };
1453
1512
  }
1454
1513
 
1455
- // Cache successful response
1456
- if (useCache && cacheContext) {
1457
- setCachedResponse(endpoint, body, data, cacheContext);
1458
- }
1459
-
1460
- // Attach after caching so the cache stores the payload alone — quota
1461
- // numbers are per-response and would be stale on a cache hit.
1462
- // Guarded: a response body can be a primitive, which cannot take a property.
1514
+ // Symbols do not serialize into the payload. The cache persists only the
1515
+ // durable warning separately; quota and request metadata remain live-only.
1463
1516
  const meta = readResponseMeta(response);
1464
1517
  this.lastResponseMeta = meta;
1465
- if (meta) {
1466
- if (data !== null && typeof data === 'object') data[RESPONSE_META] = meta;
1518
+ options.onResponseMeta?.(meta, false);
1519
+ if (meta && data !== null && typeof data === 'object') data[RESPONSE_META] = meta;
1520
+ if (useCache && cacheContext) {
1521
+ setCachedResponse(endpoint, body, data, cacheContext, meta);
1467
1522
  }
1468
1523
 
1469
1524
  return data;
@@ -1662,20 +1717,6 @@ export class NansenAPI {
1662
1717
  }, { cache: false });
1663
1718
  }
1664
1719
 
1665
- async webFetch(params = {}) {
1666
- const { urls, question } = params;
1667
- if (!urls || urls.length === 0) {
1668
- throw new NansenError('At least one URL is required', ErrorCode.MISSING_PARAM);
1669
- }
1670
- if (!question) {
1671
- throw new NansenError('A question is required', ErrorCode.MISSING_PARAM);
1672
- }
1673
- return this.request('/api/v1/search/web-fetch', {
1674
- urls,
1675
- question,
1676
- }, { cache: false });
1677
- }
1678
-
1679
1720
  async addressHistoricalBalances(params = {}) {
1680
1721
  const { address, chain = 'ethereum', filters = {}, orderBy, pagination, days = 30 } = params;
1681
1722
  if (address) requireValidAddress(address, chain);
@@ -1693,7 +1734,7 @@ export class NansenAPI {
1693
1734
  const { address, chain = 'ethereum', orderBy, pagination } = params;
1694
1735
  if (address) requireValidAddress(address, chain);
1695
1736
  return this.request('/api/v1/profiler/address/related-wallets', {
1696
- address,
1737
+ wallet_address: address,
1697
1738
  chain,
1698
1739
  order_by: orderBy,
1699
1740
  pagination
@@ -1809,7 +1850,7 @@ export class NansenAPI {
1809
1850
  const { address, chain = 'ethereum', days = 30 } = params;
1810
1851
  if (address) requireValidAddress(address, chain);
1811
1852
  return this.request('/api/v1/profiler/address/pnl-summary', {
1812
- address,
1853
+ wallet_address: address,
1813
1854
  chain,
1814
1855
  date: buildDateRange(days)
1815
1856
  });
@@ -2158,12 +2199,11 @@ export class NansenAPI {
2158
2199
  async pmMarketScreener(params = {}) {
2159
2200
  const { orderBy, sortBy = 'volume_24hr', query = '', status = '', tags, minLiquidity, maxLiquidity, maxUniqueTraders24h, minVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, minPrice, maxPrice, pagination } = params;
2160
2201
  const body = {
2161
- sort_by: sortBy,
2202
+ order_by: orderBy || [{ field: sortBy, direction: 'DESC' }],
2162
2203
  query,
2163
2204
  status,
2164
2205
  pagination
2165
2206
  };
2166
- if (orderBy) body.order_by = orderBy;
2167
2207
  if (tags && tags.length) body.tags = tags;
2168
2208
  if (minLiquidity != null) body.min_liquidity = minLiquidity;
2169
2209
  if (maxLiquidity != null) body.max_liquidity = maxLiquidity;
@@ -2182,12 +2222,11 @@ export class NansenAPI {
2182
2222
  async pmEventScreener(params = {}) {
2183
2223
  const { orderBy, sortBy = 'volume_24hr', query = '', status = '', tags, minLiquidity, maxLiquidity, maxUniqueTraders24h, minVolume24hr, negRisk, minOpenInterest, maxOpenInterest, endDateBefore, endDateAfter, pagination } = params;
2184
2224
  const body = {
2185
- sort_by: sortBy,
2225
+ order_by: orderBy || [{ field: sortBy, direction: 'DESC' }],
2186
2226
  query,
2187
2227
  status,
2188
2228
  pagination
2189
2229
  };
2190
- if (orderBy) body.order_by = orderBy;
2191
2230
  if (tags && tags.length) body.tags = tags;
2192
2231
  if (minLiquidity != null) body.min_liquidity = minLiquidity;
2193
2232
  if (maxLiquidity != null) body.max_liquidity = maxLiquidity;
@@ -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
+ }
@@ -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;
@@ -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) {