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.
package/src/privy.js CHANGED
@@ -8,13 +8,12 @@
8
8
 
9
9
  import fs from "fs";
10
10
  import path from "path";
11
- import { parsePaymentRequirements } from "./x402.js";
11
+ import { parsePaymentRequirements, rankRequirements } from "./x402.js";
12
12
  import { hasSufficientEvmPaymentBalance, hasSufficientSvmPaymentBalance } from "./x402-payment-balance.js";
13
13
  import { isEvmNetwork } from "./x402-evm.js";
14
- import { mkdirPrivateSync, readWalletJson, withWalletLock, writeWalletJsonAtomic } from "./wallet.js";
14
+ import { mkdirPrivateSync, readWalletJson, validateWalletName, withWalletLock, writeWalletJsonAtomic } from "./wallet.js";
15
15
  import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo, signWithSessionCharge } from "./x402-policy.js";
16
16
  import {
17
- isSvmNetwork,
18
17
  getSolanaRpcUrl,
19
18
  fetchRecentBlockhash,
20
19
  buildUnsignedSvmTransaction,
@@ -209,10 +208,7 @@ function getClient() {
209
208
  * Mirrors createWallet() in wallet.js but for Privy server wallets.
210
209
  */
211
210
  export async function createPrivyWalletPair(name) {
212
- const WALLET_NAME_RE = /^[a-zA-Z0-9_-]{1,64}$/;
213
- if (!name || !WALLET_NAME_RE.test(name)) {
214
- throw new Error("Wallet name must be 1-64 characters: letters, numbers, hyphens, underscores only");
215
- }
211
+ validateWalletName(name, { creating: true });
216
212
 
217
213
  const walletsDir = path.join(process.env.HOME || process.env.USERPROFILE || "", ".nansen", "wallets");
218
214
  const walletFile = path.join(walletsDir, `${name}.json`);
@@ -362,6 +358,11 @@ async function getPrivySolanaWallet(client) {
362
358
  * Same yield contract as createPaymentSignatures() in x402.js:
363
359
  * { signature, network, asset, payment, releaseCharge }
364
360
  *
361
+ * Options are tried cheapest first, in the order rankRequirements gives the
362
+ * local and WalletConnect signers. The caller stops at the first payment the
363
+ * server accepts, so server order would let a pricier option be paid while a
364
+ * cheaper one sat in the same response.
365
+ *
365
366
  * @param {Response} response - The 402 HTTP response
366
367
  * @param {string} url - The original request URL
367
368
  * @param {object} [options] - { onCapRefusal }, called with the reason when the session cap refuses an option
@@ -373,113 +374,151 @@ export async function* createPrivyPaymentSignatures(response, url, options = {})
373
374
 
374
375
  const client = getClient();
375
376
 
376
- // EVM requirements
377
- const evmRequirements = requirements.filter((r) => isEvmNetwork(r.network));
378
- if (evmRequirements.length > 0) {
379
- const evmWallet = await getPrivyEvmWallet(client);
380
- if (evmWallet) {
381
- for (const requirement of evmRequirements) {
382
- const decision = evaluatePaymentRequirement(requirement);
383
- if (!decision.ok) {
384
- console.error(`[x402] ${decision.reason}`);
385
- continue;
386
- }
387
- try {
388
- if (!await hasSufficientEvmPaymentBalance(requirement, evmWallet.address)) continue;
389
- const typedData = buildEIP712TypedData({
390
- fromAddress: evmWallet.address,
391
- requirement,
392
- });
393
-
394
- const signed = await signWithSessionCharge(decision, async () => {
395
- const signResult = await client.ethSignTypedDataV4(evmWallet.id, typedData);
396
- const signature = signResult.data?.signature || signResult.signature;
397
- if (!signature) throw new Error('Privy returned no signature');
398
-
399
- const authorization = {
400
- from: evmWallet.address,
401
- to: resolvePayTo(requirement),
402
- value: resolvePaymentAmount(requirement).toString(),
403
- validAfter: typedData.message.validAfter.toString(),
404
- validBefore: typedData.message.validBefore.toString(),
405
- nonce: typedData.message.nonce,
406
- };
407
-
408
- return buildPaymentSignatureHeader({
409
- signature,
410
- authorization,
411
- resource: { url, description: "", mimeType: "" },
412
- accepted: requirement,
413
- });
414
- });
415
- if (!signed.ok) {
416
- console.error(`[x402] ${signed.reason}`);
417
- options.onCapRefusal?.(signed.reason);
418
- continue;
419
- }
420
-
421
- yield { signature: signed.value, network: requirement.network, asset: requirement.asset, payment: decision, releaseCharge: signed.release };
422
- } catch (err) {
423
- console.error(`[x402] Privy EVM signing failed for ${requirement.network}: ${err.message}`);
424
- continue;
425
- }
426
- }
377
+ // rankRequirements keeps only EVM and Solana options. Each wallet is looked
378
+ // up once, on the first option for its chain.
379
+ let evmWallet;
380
+ let solWallet;
381
+ let lookupError;
382
+ let signedAny = false;
383
+ const onLookupError = (err) => { if (!lookupError) lookupError = err; };
384
+ for (const requirement of rankRequirements(requirements)) {
385
+ if (isEvmNetwork(requirement.network)) {
386
+ if (evmWallet === undefined) evmWallet = await lookupPrivyWallet('EVM', () => getPrivyEvmWallet(client), onLookupError);
387
+ if (!evmWallet) continue;
388
+ const item = await signPrivyEvmRequirement(client, evmWallet, requirement, url, options);
389
+ if (item) { signedAny = true; yield item; }
427
390
  } else {
428
- console.error('[x402] No Privy EVM wallet found for payment signing');
391
+ if (solWallet === undefined) solWallet = await lookupPrivyWallet('Solana', () => getPrivySolanaWallet(client), onLookupError);
392
+ if (!solWallet) continue;
393
+ const item = await signPrivySolanaRequirement(client, solWallet, requirement, url, options);
394
+ if (item) { signedAny = true; yield item; }
429
395
  }
430
396
  }
397
+ // A failed lookup only skips its own chain. When nothing was signed at all,
398
+ // surface the lookup error so a Privy setup problem keeps its reason.
399
+ if (!signedAny && lookupError) throw lookupError;
400
+ }
431
401
 
432
- // Solana requirements
433
- const svmRequirements = requirements.filter((r) => isSvmNetwork(r.network));
434
- if (svmRequirements.length > 0) {
435
- const solWallet = await getPrivySolanaWallet(client);
436
- if (solWallet) {
437
- for (const requirement of svmRequirements) {
438
- const svmDecision = evaluatePaymentRequirement(requirement);
439
- if (!svmDecision.ok) {
440
- console.error(`[x402] ${svmDecision.reason}`);
441
- continue;
442
- }
443
- try {
444
- if (!await hasSufficientSvmPaymentBalance(requirement, solWallet.address)) continue;
445
- const rpcUrl = getSolanaRpcUrl(requirement.network);
446
- const recentBlockhash = await fetchRecentBlockhash(rpcUrl);
447
-
448
- const { txBase64 } = buildUnsignedSvmTransaction(
449
- requirement,
450
- solWallet.address,
451
- recentBlockhash,
452
- );
453
-
454
- const signed = await signWithSessionCharge(svmDecision, async () => {
455
- const signResult = await client.signSolanaTransaction(solWallet.id, txBase64);
456
- const signedTx = signResult.data?.signed_transaction || signResult.signed_transaction;
457
- if (!signedTx) throw new Error('Privy returned no signed transaction');
458
-
459
- const payload = {
460
- x402Version: 2,
461
- payload: { transaction: signedTx },
462
- accepted: requirement,
463
- };
464
- if (url) {
465
- payload.resource = { url };
466
- }
467
- return Buffer.from(JSON.stringify(payload)).toString("base64");
468
- });
469
- if (!signed.ok) {
470
- console.error(`[x402] ${signed.reason}`);
471
- options.onCapRefusal?.(signed.reason);
472
- continue;
473
- }
402
+ /**
403
+ * Look up the Privy wallet for one chain. A failed lookup only skips that
404
+ * chain's options, so the remaining ranked options on the other chain are
405
+ * still tried. The error is passed to onError so the caller can report it
406
+ * if no option gets signed.
407
+ */
408
+ async function lookupPrivyWallet(chain, lookup, onError) {
409
+ try {
410
+ const wallet = await lookup();
411
+ if (!wallet) console.error(`[x402] No Privy ${chain} wallet found for payment signing`);
412
+ return wallet || null;
413
+ } catch (err) {
414
+ console.error(`[x402] Privy ${chain} wallet lookup failed: ${err.message}`);
415
+ onError(err);
416
+ return null;
417
+ }
418
+ }
474
419
 
475
- yield { signature: signed.value, network: requirement.network, asset: requirement.asset, payment: svmDecision, releaseCharge: signed.release };
476
- } catch (err) {
477
- console.error(`[x402] Privy Solana signing failed for ${requirement.network}: ${err.message}`);
478
- continue;
479
- }
420
+ /**
421
+ * Sign one EVM option with the Privy wallet, or return null to skip it.
422
+ */
423
+ async function signPrivyEvmRequirement(client, evmWallet, requirement, url, options) {
424
+ const decision = evaluatePaymentRequirement(requirement);
425
+ if (!decision.ok) {
426
+ console.error(`[x402] ${decision.reason}`);
427
+ return null;
428
+ }
429
+ // Privy signs an EIP-3009 TransferWithAuthorization. A Permit2 or unknown
430
+ // transfer method needs a different signature, which the server rejects as
431
+ // EIP-3009, so skip it like the WalletConnect signer does.
432
+ const method = requirement.extra?.assetTransferMethod;
433
+ if (method && method !== 'eip3009') {
434
+ console.error(`[x402] Skipping ${requirement.network} option: Privy wallets sign only EIP-3009 payments, not assetTransferMethod "${method}".`);
435
+ return null;
436
+ }
437
+ try {
438
+ if (!await hasSufficientEvmPaymentBalance(requirement, evmWallet.address)) return null;
439
+ const typedData = buildEIP712TypedData({
440
+ fromAddress: evmWallet.address,
441
+ requirement,
442
+ });
443
+
444
+ const signed = await signWithSessionCharge(decision, async () => {
445
+ const signResult = await client.ethSignTypedDataV4(evmWallet.id, typedData);
446
+ const signature = signResult.data?.signature || signResult.signature;
447
+ if (!signature) throw new Error('Privy returned no signature');
448
+
449
+ const authorization = {
450
+ from: evmWallet.address,
451
+ to: resolvePayTo(requirement),
452
+ value: resolvePaymentAmount(requirement).toString(),
453
+ validAfter: typedData.message.validAfter.toString(),
454
+ validBefore: typedData.message.validBefore.toString(),
455
+ nonce: typedData.message.nonce,
456
+ };
457
+
458
+ return buildPaymentSignatureHeader({
459
+ signature,
460
+ authorization,
461
+ resource: { url, description: "", mimeType: "" },
462
+ accepted: requirement,
463
+ });
464
+ });
465
+ if (!signed.ok) {
466
+ console.error(`[x402] ${signed.reason}`);
467
+ options.onCapRefusal?.(signed.reason);
468
+ return null;
469
+ }
470
+
471
+ return { signature: signed.value, network: requirement.network, asset: requirement.asset, payment: decision, releaseCharge: signed.release };
472
+ } catch (err) {
473
+ console.error(`[x402] Privy EVM signing failed for ${requirement.network}: ${err.message}`);
474
+ return null;
475
+ }
476
+ }
477
+
478
+ /**
479
+ * Sign one Solana option with the Privy wallet, or return null to skip it.
480
+ */
481
+ async function signPrivySolanaRequirement(client, solWallet, requirement, url, options) {
482
+ const svmDecision = evaluatePaymentRequirement(requirement);
483
+ if (!svmDecision.ok) {
484
+ console.error(`[x402] ${svmDecision.reason}`);
485
+ return null;
486
+ }
487
+ try {
488
+ if (!await hasSufficientSvmPaymentBalance(requirement, solWallet.address)) return null;
489
+ const rpcUrl = getSolanaRpcUrl(requirement.network);
490
+ const recentBlockhash = await fetchRecentBlockhash(rpcUrl);
491
+
492
+ const { txBase64 } = buildUnsignedSvmTransaction(
493
+ requirement,
494
+ solWallet.address,
495
+ recentBlockhash,
496
+ );
497
+
498
+ const signed = await signWithSessionCharge(svmDecision, async () => {
499
+ const signResult = await client.signSolanaTransaction(solWallet.id, txBase64);
500
+ const signedTx = signResult.data?.signed_transaction || signResult.signed_transaction;
501
+ if (!signedTx) throw new Error('Privy returned no signed transaction');
502
+
503
+ const payload = {
504
+ x402Version: 2,
505
+ payload: { transaction: signedTx },
506
+ accepted: requirement,
507
+ };
508
+ if (url) {
509
+ payload.resource = { url };
480
510
  }
481
- } else {
482
- console.error('[x402] No Privy Solana wallet found for payment signing');
511
+ return Buffer.from(JSON.stringify(payload)).toString("base64");
512
+ });
513
+ if (!signed.ok) {
514
+ console.error(`[x402] ${signed.reason}`);
515
+ options.onCapRefusal?.(signed.reason);
516
+ return null;
483
517
  }
518
+
519
+ return { signature: signed.value, network: requirement.network, asset: requirement.asset, payment: svmDecision, releaseCharge: signed.release };
520
+ } catch (err) {
521
+ console.error(`[x402] Privy Solana signing failed for ${requirement.network}: ${err.message}`);
522
+ return null;
484
523
  }
485
524
  }
@@ -37,12 +37,28 @@ export function buildPagination(options) {
37
37
  // Parse simple sort syntax: "field:direction" or "field" (defaults to DESC)
38
38
  export function parseSort(sortOption, orderByOption) {
39
39
  // If --order-by is provided, use it (full JSON control)
40
- if (orderByOption) return orderByOption;
40
+ if (orderByOption) {
41
+ const isEntry = e => e !== null && typeof e === 'object' && !Array.isArray(e)
42
+ && typeof e.field === 'string' && e.field.trim() !== '';
43
+ if (!Array.isArray(orderByOption) || !orderByOption.every(isEntry)) {
44
+ throw new NansenError(
45
+ `--order-by must be a JSON array of {"field", "direction"} objects, e.g. --order-by '[{"field":"value_usd","direction":"DESC"}]'`,
46
+ ErrorCode.INVALID_PARAMS,
47
+ );
48
+ }
49
+ return orderByOption;
50
+ }
41
51
  if (!sortOption) return undefined;
42
52
  if (typeof sortOption !== 'string') {
43
53
  throw new NansenError('--sort must be "field" or "field:direction"', ErrorCode.INVALID_PARAMS);
44
54
  }
45
55
  const parts = sortOption.split(':');
56
+ if (parts.length > 2) {
57
+ throw new NansenError(
58
+ `--sort must be "field" or "field:direction", got "${sortOption}" (e.g. --sort ${parts[0].trim()}:desc)`,
59
+ ErrorCode.INVALID_PARAMS,
60
+ );
61
+ }
46
62
  const field = parts[0].trim();
47
63
  const rawDirection = (parts[1] || '').trim();
48
64
  const direction = (rawDirection || 'desc').toUpperCase();
@@ -0,0 +1,65 @@
1
+ /**
2
+ * File-level housekeeping for the response cache directory (~/.nansen/cache),
3
+ * shared by api.js (which writes entries) and cache-inspect.js (which clears
4
+ * them). Imports nothing from either so both can use it without a cycle.
5
+ *
6
+ * Names in the directory:
7
+ * <sha256>.json a cache entry
8
+ * <sha256>.json.<pid>.<uuid>.tmp a write in progress; renamed onto the
9
+ * entry when it completes, so a leftover one
10
+ * means the writing process was killed
11
+ */
12
+
13
+ import fs from 'fs';
14
+ import path from 'path';
15
+
16
+ export const RESPONSE_ENTRY = /^[0-9a-f]{64}\.json$/;
17
+ export const RESPONSE_TEMP = /^[0-9a-f]{64}\.json\.\d+\.[0-9a-f-]{36}\.tmp$/;
18
+
19
+ // A write holds its temp file for milliseconds. Anything this old was left by
20
+ // a process that died before the rename.
21
+ export const STALE_TEMP_MS = 10 * 60 * 1000;
22
+
23
+ // Entries are never read back after their TTL (default 300s, set per call with
24
+ // --cache-ttl) and a read does not delete them, so without a sweep, requests
25
+ // that are never repeated leave files behind forever. The sweep after a cache
26
+ // write removes entries older than this, or older than the longest TTL the
27
+ // writing process has read with, whichever is longer.
28
+ export const ENTRY_MAX_AGE_MS = 24 * 60 * 60 * 1000;
29
+
30
+ /** A temp file left behind by a write that never completed. */
31
+ export function isStaleTemp(name, stat, now = Date.now()) {
32
+ return RESPONSE_TEMP.test(name) && now - stat.mtimeMs > STALE_TEMP_MS;
33
+ }
34
+
35
+ /**
36
+ * Remove stale temp files and entries older than `retentionMs` (default
37
+ * ENTRY_MAX_AGE_MS) from `dir`.
38
+ * Only regular files whose names match the two shapes above are touched; a
39
+ * symlinked or missing directory and symlinked entries are left alone.
40
+ * Returns how many files were removed.
41
+ *
42
+ * Another process may rename a fresh entry onto a path between the lstat and
43
+ * the unlink. That costs it one cache miss, never wrong data.
44
+ */
45
+ export function pruneResponseCacheDir(dir, now = Date.now(), retentionMs = ENTRY_MAX_AGE_MS) {
46
+ const dirStat = fs.lstatSync(dir, { throwIfNoEntry: false });
47
+ if (!dirStat || !dirStat.isDirectory()) return 0;
48
+ let removed = 0;
49
+ for (const name of fs.readdirSync(dir)) {
50
+ const isEntry = RESPONSE_ENTRY.test(name);
51
+ if (!isEntry && !RESPONSE_TEMP.test(name)) continue;
52
+ const file = path.join(dir, name);
53
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
54
+ if (!stat || !stat.isFile()) continue;
55
+ const stale = isEntry ? now - stat.mtimeMs > retentionMs : isStaleTemp(name, stat, now);
56
+ if (!stale) continue;
57
+ try {
58
+ fs.unlinkSync(file);
59
+ removed += 1;
60
+ } catch (error) {
61
+ if (error?.code !== 'ENOENT') throw error;
62
+ }
63
+ }
64
+ return removed;
65
+ }
@@ -66,6 +66,7 @@ export function readResponseMeta(response) {
66
66
  const planNotice = stringHeader(response, PLAN_NOTICE);
67
67
  const apiKeyNotice = stringHeader(response, API_KEY_NOTICE);
68
68
  const requestId = stringHeader(response, REQUEST_ID);
69
+ const warning = stringHeader(response, 'warning');
69
70
 
70
71
  const meta = {};
71
72
  if (requestId !== null) {
@@ -83,8 +84,9 @@ export function readResponseMeta(response) {
83
84
  // drain — not a wall-clock timestamp.
84
85
  meta.rateLimit = { limit, remaining: rateRemaining, resetSeconds };
85
86
  }
86
- if (upgradeHint !== null || planNotice !== null || apiKeyNotice !== null) {
87
+ if (upgradeHint !== null || planNotice !== null || apiKeyNotice !== null || warning !== null) {
87
88
  meta.notices = {
89
+ ...(warning !== null && { warning }),
88
90
  ...(upgradeHint !== null && { upgradeHint }),
89
91
  ...(planNotice !== null && { planNotice }),
90
92
  ...(apiKeyNotice !== null && { apiKeyNotice }),
@@ -102,11 +104,13 @@ export function readResponseMeta(response) {
102
104
  export function aggregatePaginatedResponseMeta(pages) {
103
105
  if (!Array.isArray(pages) || pages.length === 0) return null;
104
106
 
107
+ const warning = [...new Set(pages.map(page => page.meta?.notices?.warning).filter(Boolean))].join(', ');
105
108
  const livePages = pages.filter(page => !page.cached);
106
109
  const metas = livePages.map(page => page.meta);
107
110
  const present = metas.filter(Boolean);
108
111
  if (livePages.length === 0) {
109
112
  return {
113
+ ...(warning && { notices: { warning } }),
110
114
  credits: { used: 0, remaining: null, cost: 0 },
111
115
  pagination: { pagesFetched: pages.length, livePages: 0, cachedPages: pages.length },
112
116
  };
@@ -134,6 +138,7 @@ export function aggregatePaginatedResponseMeta(pages) {
134
138
 
135
139
  const notices = {};
136
140
  for (const meta of present) Object.assign(notices, meta.notices || {});
141
+ if (warning) notices.warning = warning;
137
142
  if (Object.keys(notices).length > 0) result.notices = notices;
138
143
 
139
144
  result.pagination = {
@@ -147,12 +152,13 @@ export function aggregatePaginatedResponseMeta(pages) {
147
152
  /**
148
153
  * Yield notice strings for any server-set advisory headers.
149
154
  * Each yields a `⚠️ <message>` line for stderr.
150
- * Order: apiKeyNotice (most urgent) → upgradeHint → planNotice.
155
+ * Order: API warning → apiKeyNotice → upgradeHint → planNotice.
151
156
  */
152
157
  export function noticeWarnings(meta) {
153
158
  const notices = meta?.notices;
154
159
  if (!notices) return [];
155
160
  const out = [];
161
+ if (notices.warning) out.push(`⚠️ ${notices.warning}`);
156
162
  if (notices.apiKeyNotice) out.push(`⚠️ ${notices.apiKeyNotice}`);
157
163
  if (notices.upgradeHint) out.push(`ℹ️ ${notices.upgradeHint}`);
158
164
  if (notices.planNotice) out.push(`ℹ️ ${notices.planNotice}`);