nansen-cli 1.46.0 → 2.0.1

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 (78) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +157 -14
  3. package/docs/browser-login.md +123 -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 +89 -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 +288 -0
  50. package/src/bridge.js +126 -21
  51. package/src/cache-inspect.js +345 -0
  52. package/src/cli.js +473 -199
  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/limit-order.js +1 -1
  61. package/src/mcp-client-config.js +169 -0
  62. package/src/mcp-client-config.json +17 -0
  63. package/src/mcp-verify.js +6 -5
  64. package/src/perp.js +41 -0
  65. package/src/privy.js +12 -12
  66. package/src/response-meta.js +56 -1
  67. package/src/rpc-urls.js +9 -11
  68. package/src/schema.json +185 -8
  69. package/src/semver.js +23 -4
  70. package/src/swap-simulation.js +35 -30
  71. package/src/telemetry.js +20 -0
  72. package/src/trading.js +266 -29
  73. package/src/transfer.js +53 -6
  74. package/src/update-check.js +9 -1
  75. package/src/wallet.js +107 -17
  76. package/src/walletconnect-trading.js +24 -5
  77. package/src/x402-svm.js +123 -64
  78. package/src/x402.js +46 -14
@@ -17,6 +17,14 @@ const CACHE_FILE = path.join(CONFIG_DIR, 'update-check.json');
17
17
  const STALE_MS = 24 * 60 * 60 * 1000; // 24 hours
18
18
  const PACKAGE_NAME = 'nansen-cli';
19
19
 
20
+ /** How long a recorded update check stays fresh. */
21
+ export const UPDATE_CHECK_TTL_MS = STALE_MS;
22
+
23
+ /** Absolute path of the update check cache file, for `nansen cache stats` and `clear`. */
24
+ export function getUpdateCheckFile() {
25
+ return CACHE_FILE;
26
+ }
27
+
20
28
  /**
21
29
  * Compare two semver strings. Returns true if latest > current.
22
30
  * Exported so `nansen doctor` reports upgrade state with identical semantics.
@@ -150,7 +158,7 @@ export function scheduleUpdateCheck() {
150
158
  // Check staleness
151
159
  if (fs.existsSync(CACHE_FILE)) {
152
160
  const { checkedAt } = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf8'));
153
- if (checkedAt && Date.now() - checkedAt < STALE_MS) return;
161
+ if (Number.isFinite(checkedAt) && checkedAt !== 0 && Date.now() - checkedAt < STALE_MS) return;
154
162
  }
155
163
 
156
164
  const child = childProcess.spawn(process.execPath, ['-e', buildCheckScript(CONFIG_DIR, CACHE_FILE)], {
package/src/wallet.js CHANGED
@@ -207,9 +207,87 @@ export function generateSolanaWallet() {
207
207
 
208
208
  // ============= Storage =============
209
209
 
210
+ /**
211
+ * Create a private directory (and any missing parents) owner-only. mkdir's
212
+ * mode is filtered through the process umask — a 0277 umask leaves 0500, so
213
+ * the owner could not create files inside — so each directory this creates
214
+ * has its mode pinned afterwards. Existing directories are left untouched.
215
+ */
216
+ export function mkdirPrivateSync(dir) {
217
+ const missing = [];
218
+ for (let cur = dir; !fs.existsSync(cur); cur = path.dirname(cur)) {
219
+ missing.unshift(cur);
220
+ if (path.dirname(cur) === cur) break;
221
+ }
222
+ for (const d of missing) {
223
+ try {
224
+ fs.mkdirSync(d, { mode: 0o700 });
225
+ } catch (err) {
226
+ // Another nansen process may have created it between the existence
227
+ // check and here; the chmod below still applies.
228
+ if (err.code !== 'EEXIST') throw err;
229
+ }
230
+ fs.chmodSync(d, 0o700);
231
+ }
232
+ }
233
+
210
234
  function ensureWalletsDir() {
211
- if (!fs.existsSync(getWalletsDir())) {
212
- fs.mkdirSync(getWalletsDir(), { mode: 0o700, recursive: true });
235
+ mkdirPrivateSync(getWalletsDir());
236
+ }
237
+
238
+ /**
239
+ * Write a wallet-subsystem JSON file (config.json or a <name>.json key file)
240
+ * so that a concurrent reader always sees either the previous complete file
241
+ * or the new complete file, never a truncated one: write to a pid-suffixed
242
+ * temp file, pin its mode to 0600 on the fd (writeFileSync's mode option is
243
+ * filtered through the umask), then rename over the target. Mirrors the
244
+ * writeAtomic helpers in cost-cache.js / update-check.js, which the key files
245
+ * — the highest-value files this CLI owns — never got.
246
+ */
247
+ // Every wallet-subsystem path is built from getWalletsDir() plus a name that
248
+ // validateWalletName() already confined to [a-zA-Z0-9_-]; this re-checks the
249
+ // resolved path so the helpers below can never be pointed outside that
250
+ // directory by a future caller.
251
+ function assertWalletsDirPath(filePath) {
252
+ const dir = path.resolve(getWalletsDir());
253
+ const resolved = path.resolve(filePath);
254
+ if (path.dirname(resolved) !== dir) {
255
+ throw new Error(`Refusing to access ${filePath}: not inside the wallets directory`);
256
+ }
257
+ return resolved;
258
+ }
259
+
260
+ export function writeWalletJsonAtomic(filePath, value) {
261
+ filePath = assertWalletsDirPath(filePath);
262
+ const tmp = `${filePath}.${process.pid}.tmp`;
263
+ let fd;
264
+ try {
265
+ fd = fs.openSync(tmp, 'w', 0o600);
266
+ fs.fchmodSync(fd, 0o600);
267
+ fs.writeFileSync(fd, JSON.stringify(value, null, 2));
268
+ fs.closeSync(fd);
269
+ fd = undefined;
270
+ fs.renameSync(tmp, filePath);
271
+ } catch (err) {
272
+ if (fd !== undefined) {
273
+ try { fs.closeSync(fd); } catch { /* already closed */ }
274
+ }
275
+ try { fs.unlinkSync(tmp); } catch { /* temp file may not exist */ }
276
+ throw err;
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Read and parse a wallet-subsystem JSON file. A file that exists but does
282
+ * not parse (torn write, disk error, manual edit) is reported by name instead
283
+ * of surfacing as a bare SyntaxError from deep inside a wallet command.
284
+ */
285
+ export function readWalletJson(filePath) {
286
+ const raw = fs.readFileSync(assertWalletsDirPath(filePath), 'utf8');
287
+ try {
288
+ return JSON.parse(raw);
289
+ } catch (err) {
290
+ throw new Error(`${filePath} is not valid JSON (${err.message}). Restore it from a backup before running wallet commands.`, { cause: err });
213
291
  }
214
292
  }
215
293
 
@@ -227,12 +305,12 @@ export function getWalletConfig() {
227
305
  return { defaultWallet: null, passwordHash: null };
228
306
  }
229
307
  warnIfInsecurePerms(getWalletConfigPath());
230
- return JSON.parse(fs.readFileSync(getWalletConfigPath(), 'utf8'));
308
+ return readWalletJson(getWalletConfigPath());
231
309
  }
232
310
 
233
311
  function saveWalletConfig(config) {
234
312
  ensureWalletsDir();
235
- fs.writeFileSync(getWalletConfigPath(), JSON.stringify(config, null, 2), { mode: 0o600 });
313
+ writeWalletJsonAtomic(getWalletConfigPath(), config);
236
314
  }
237
315
 
238
316
  const WALLET_NAME_RE = /^[a-zA-Z0-9_-]{1,64}$/;
@@ -390,17 +468,27 @@ export function listWallets() {
390
468
  const config = getWalletConfig();
391
469
  const files = fs.readdirSync(getWalletsDir()).filter(f => f.endsWith('.json') && f !== 'config.json');
392
470
 
393
- const wallets = files.map(f => {
394
- const data = JSON.parse(fs.readFileSync(path.join(getWalletsDir(), f), 'utf8'));
395
- return {
471
+ const wallets = [];
472
+ for (const f of files) {
473
+ const filePath = path.join(getWalletsDir(), f);
474
+ let data;
475
+ try {
476
+ data = readWalletJson(filePath);
477
+ } catch (err) {
478
+ // One damaged file must not hide every other wallet — report it and
479
+ // keep listing the rest.
480
+ console.error(`⚠️ Skipping ${filePath}: ${err.message}`);
481
+ continue;
482
+ }
483
+ wallets.push({
396
484
  name: data.name,
397
485
  provider: data.provider || 'local',
398
486
  evm: data.evm?.address || null,
399
487
  solana: data.solana?.address || null,
400
488
  createdAt: data.createdAt,
401
489
  isDefault: data.name === config.defaultWallet,
402
- };
403
- });
490
+ });
491
+ }
404
492
 
405
493
  return { wallets, defaultWallet: config.defaultWallet };
406
494
  }
@@ -432,7 +520,7 @@ export function createWallet(name, password) {
432
520
  .filter(f => f.endsWith('.json') && f !== 'config.json')
433
521
  .filter(f => {
434
522
  try {
435
- const data = JSON.parse(fs.readFileSync(path.join(walletsDir, f), 'utf8'));
523
+ const data = readWalletJson(path.join(walletsDir, f));
436
524
  return !data.provider || data.provider === 'local';
437
525
  } catch { return true; }
438
526
  });
@@ -461,7 +549,7 @@ export function createWallet(name, password) {
461
549
  },
462
550
  };
463
551
 
464
- fs.writeFileSync(walletFile, JSON.stringify(wallet, null, 2), { mode: 0o600 });
552
+ writeWalletJsonAtomic(walletFile, wallet);
465
553
 
466
554
  // Set as default if it's the first wallet
467
555
  if (!config.defaultWallet) {
@@ -483,7 +571,7 @@ export function createWallet(name, password) {
483
571
  export function showWallet(name) {
484
572
  const walletFile = requireWalletFile(name);
485
573
 
486
- const data = JSON.parse(fs.readFileSync(walletFile, 'utf8'));
574
+ const data = readWalletJson(walletFile);
487
575
  const config = getWalletConfig();
488
576
  const isPrivy = data.provider === 'privy';
489
577
 
@@ -509,7 +597,7 @@ export function showWallet(name) {
509
597
  export function exportWallet(name, password) {
510
598
  const walletFile = requireWalletFile(name);
511
599
 
512
- const data = JSON.parse(fs.readFileSync(walletFile, 'utf8'));
600
+ const data = readWalletJson(walletFile);
513
601
  if (data.provider && data.provider !== 'local') {
514
602
  throw new Error(`${data.provider} wallets don't support key export. Keys are managed by the provider.`);
515
603
  }
@@ -551,7 +639,7 @@ export function setDefaultWallet(name) {
551
639
  export async function deleteWallet(name, password) {
552
640
  const walletFile = requireWalletFile(name);
553
641
 
554
- const data = JSON.parse(fs.readFileSync(walletFile, 'utf8'));
642
+ const data = readWalletJson(walletFile);
555
643
  const config = getWalletConfig();
556
644
 
557
645
  if (data.provider && data.provider !== 'local') {
@@ -564,7 +652,9 @@ export async function deleteWallet(name, password) {
564
652
 
565
653
  fs.unlinkSync(walletFile);
566
654
 
567
- const remaining = fs.readdirSync(getWalletsDir()).filter(f => f.endsWith('.json') && f !== 'config.json');
655
+ const remaining = fs.readdirSync(getWalletsDir())
656
+ .filter(f => f.endsWith('.json') && f !== 'config.json')
657
+ .filter(f => { try { readWalletJson(path.join(getWalletsDir(), f)); return true; } catch { return false; } });
568
658
 
569
659
  if (remaining.length === 0) {
570
660
  config.defaultWallet = null;
@@ -932,7 +1022,7 @@ export function buildWalletCommands(deps = {}) {
932
1022
  // dir and cannot traverse. deleteWallet() re-validates below.
933
1023
  let isPrivy = false;
934
1024
  try {
935
- const data = JSON.parse(fs.readFileSync(getWalletFile(name), 'utf8'));
1025
+ const data = readWalletJson(getWalletFile(name));
936
1026
  if (data.provider === 'privy') isPrivy = true;
937
1027
  } catch { /* invalid/missing name; deleteWallet will validate and throw */ }
938
1028
 
@@ -994,7 +1084,7 @@ export function buildWalletCommands(deps = {}) {
994
1084
  // getWalletFile() runs validateWalletName(), confining the path to
995
1085
  // the wallets dir; an invalid name throws and is ignored here, and
996
1086
  // the real wallet load downstream validates again.
997
- const data = JSON.parse(fs.readFileSync(getWalletFile(walletName), 'utf8'));
1087
+ const data = readWalletJson(getWalletFile(walletName));
998
1088
  if (data.provider === 'privy') isPrivyWallet = true;
999
1089
  }
1000
1090
  } catch { /* ignore */ }
@@ -25,16 +25,35 @@ export function parseWcJson(output) {
25
25
  const startIdx = lines.findIndex(l => l.trimStart().startsWith('{'));
26
26
  if (startIdx === -1) throw new Error('No JSON output from walletconnect');
27
27
 
28
- // Handle multi-line JSON: collect lines until braces balance
29
- let braces = 0;
28
+ // Handle multi-line JSON: collect lines until braces balance. A brace
29
+ // inside a string value ("... retried } ok") is not structural, so track
30
+ // string and escape state while scanning — counting it would end the object
31
+ // early and fail to parse a perfectly valid result.
32
+ let depth = 0;
33
+ let inString = false;
34
+ let escaped = false;
30
35
  const jsonLines = [];
31
36
  for (let i = startIdx; i < lines.length; i++) {
32
37
  jsonLines.push(lines[i]);
33
38
  for (const ch of lines[i]) {
34
- if (ch === '{') braces++;
35
- else if (ch === '}') braces--;
39
+ if (escaped) {
40
+ escaped = false;
41
+ } else if (inString) {
42
+ if (ch === '\\') escaped = true;
43
+ else if (ch === '"') inString = false;
44
+ } else if (ch === '"') {
45
+ inString = true;
46
+ } else if (ch === '{') {
47
+ depth++;
48
+ } else if (ch === '}') {
49
+ depth--;
50
+ }
36
51
  }
37
- if (braces === 0) break;
52
+ // A JSON string cannot contain a raw newline, so any unterminated quote is
53
+ // a line-local anomaly rather than a string continuing onto the next line.
54
+ inString = false;
55
+ escaped = false;
56
+ if (depth === 0) break;
38
57
  }
39
58
  return JSON.parse(jsonLines.join('\n'));
40
59
  }
package/src/x402-svm.js CHANGED
@@ -8,6 +8,7 @@ import { base58Encode, base58DecodePubkey } from './wallet.js';
8
8
  import { encodeCompactU16, deriveATA as _deriveATA } from './transfer.js';
9
9
  import { resolvePaymentAmount, resolvePayTo } from './x402-policy.js';
10
10
  import { SOLANA_MAINNET_NETWORK } from './x402-tokens.js';
11
+ import { CHAIN_RPCS } from './rpc-urls.js';
11
12
 
12
13
  // ============= Constants =============
13
14
 
@@ -20,6 +21,16 @@ const _SYSTEM_PROGRAM = '11111111111111111111111111111111';
20
21
  const DEFAULT_COMPUTE_UNIT_LIMIT = 20000;
21
22
  const DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 1;
22
23
 
24
+ // Upper bound on a single blockhash RPC round-trip. A NANSEN_SOLANA_RPC
25
+ // endpoint that accepts the connection but never answers would otherwise
26
+ // stall the x402 payment fallback loop for Node's default header timeout.
27
+ const SOLANA_RPC_TIMEOUT_MS = 15_000;
28
+
29
+ // An x402 Solana payment is signed by exactly two accounts: the facilitator
30
+ // (feePayer, slot 0) and the paying wallet (slot 1).
31
+ const X402_SVM_SIGNER_COUNT = 2;
32
+ const SIGNATURE_BYTES = 64;
33
+
23
34
  // ============= PDA Derivation =============
24
35
 
25
36
  /**
@@ -36,9 +47,9 @@ export function deriveATA(ownerBase58, mintBase58, tokenProgramBase58 = TOKEN_PR
36
47
  * Build a Solana MessageV0 from accounts and instructions.
37
48
  * feePayer is always placed at account index 0, forced signer+writable,
38
49
  * regardless of whether an instruction references it directly.
39
- * Returns numRequiredSignatures alongside the bytes since it's read back out
40
- * of the header to size the signature-placeholder slots of the wrapping
41
- * unsigned transaction (see callers).
50
+ * Returns numRequiredSignatures alongside the bytes. Each caller writes a
51
+ * fixed number of signature slots and asserts this value against it, since a
52
+ * header that disagrees with the slot count is rejected at broadcast.
42
53
  */
43
54
  export function buildMessageV0({ feePayer, instructions, recentBlockhash, accounts: _accounts }) {
44
55
  // All unique accounts in order: feePayer first, then signers, then rest
@@ -237,20 +248,30 @@ export function buildUnsignedSvmTransaction(
237
248
  },
238
249
  ];
239
250
 
240
- const { messageBytes } = buildMessageV0({
251
+ const { messageBytes, numRequiredSignatures } = buildMessageV0({
241
252
  feePayer: feePayerStr,
242
253
  instructions,
243
254
  recentBlockhash,
244
255
  accounts: null,
245
256
  });
257
+ // The header must agree with the signature slots written below. A
258
+ // server-supplied feePayer equal to the paying wallet collapses the two
259
+ // signers into one, and the transaction would fail sanitization at broadcast.
260
+ if (numRequiredSignatures !== X402_SVM_SIGNER_COUNT) {
261
+ const cause = feePayerStr === walletAddress
262
+ ? `its feePayer is the paying wallet (${walletAddress}) instead of a facilitator account`
263
+ : `its transaction requires ${numRequiredSignatures} signatures instead of ${X402_SVM_SIGNER_COUNT}`;
264
+ throw new Error(
265
+ `Cannot pay this x402 Solana option: ${cause}. ` +
266
+ 'Another payment option will be tried; if none succeeds, pay on another network or report this payment option to Nansen.',
267
+ );
268
+ }
246
269
 
247
270
  // Build transaction: compact-u16(numSignatures) + signatures + message
248
- // 2 signatures: [facilitator placeholder (64 zero bytes), client placeholder (64 zero bytes)]
249
- const numSigs = encodeCompactU16(2);
271
+ // [facilitator placeholder, client placeholder], 64 zero bytes each
250
272
  const txBytes = Buffer.concat([
251
- numSigs,
252
- Buffer.alloc(64), // facilitator placeholder
253
- Buffer.alloc(64), // client placeholder
273
+ encodeCompactU16(X402_SVM_SIGNER_COUNT),
274
+ Buffer.alloc(X402_SVM_SIGNER_COUNT * SIGNATURE_BYTES),
254
275
  messageBytes,
255
276
  ]);
256
277
 
@@ -272,7 +293,7 @@ export function createSvmPaymentPayload(
272
293
  decimals = 6,
273
294
  tokenProgram = TOKEN_PROGRAM,
274
295
  ) {
275
- const { messageBytes } = buildUnsignedSvmTransaction(
296
+ const { messageBytes, txBase64: unsignedTxBase64 } = buildUnsignedSvmTransaction(
276
297
  requirements,
277
298
  walletAddress,
278
299
  recentBlockhash,
@@ -283,14 +304,11 @@ export function createSvmPaymentPayload(
283
304
  // Sign: client signs the full message (with 0x80 version prefix already included)
284
305
  const clientSignature = signEd25519(messageBytes, keypairHex);
285
306
 
286
- // Rebuild transaction with the real client signature at slot 1
287
- const numSigs = encodeCompactU16(2);
288
- const txBytes = Buffer.concat([
289
- numSigs,
290
- Buffer.alloc(64), // facilitator placeholder
291
- clientSignature,
292
- messageBytes,
293
- ]);
307
+ // Write the client signature into slot 1 of the unsigned transaction, so
308
+ // the wire layout is built in one place.
309
+ const txBytes = Buffer.from(unsignedTxBase64, 'base64');
310
+ const clientSlotOffset = encodeCompactU16(X402_SVM_SIGNER_COUNT).length + SIGNATURE_BYTES;
311
+ clientSignature.copy(txBytes, clientSlotOffset);
294
312
 
295
313
  const txBase64 = txBytes.toString('base64');
296
314
 
@@ -308,70 +326,111 @@ export function createSvmPaymentPayload(
308
326
  return Buffer.from(JSON.stringify(payload)).toString('base64');
309
327
  }
310
328
 
329
+ function isHttpUrl(value) {
330
+ if (typeof value !== 'string') return false;
331
+ try {
332
+ const { protocol } = new URL(value);
333
+ return protocol === 'http:' || protocol === 'https:';
334
+ } catch {
335
+ return false;
336
+ }
337
+ }
338
+
311
339
  /**
312
340
  * Fetch recent blockhash from Solana RPC.
341
+ *
342
+ * Defaults to the shared RPC registry so NANSEN_SOLANA_RPC is honoured even
343
+ * for an argless call; every production caller passes the URL explicitly.
313
344
  */
314
- export async function fetchRecentBlockhash(rpcUrl = 'https://api.mainnet-beta.solana.com') {
315
- let response;
316
- try {
317
- response = await fetch(rpcUrl, {
318
- method: 'POST',
319
- headers: { 'Content-Type': 'application/json' },
320
- body: JSON.stringify({
321
- jsonrpc: '2.0',
322
- id: 1,
323
- method: 'getLatestBlockhash',
324
- params: [{ commitment: 'finalized' }],
325
- }),
326
- });
327
- } catch (err) {
345
+ export async function fetchRecentBlockhash(rpcUrl = CHAIN_RPCS.solana) {
346
+ // Validate up front and never echo the raw value. A private RPC URL usually
347
+ // carries an API key in its query string, and Node's own parse failure
348
+ // ("Failed to parse URL from <value>") would otherwise copy it into the
349
+ // error message that the Privy and local-wallet fallback loops print.
350
+ if (!isHttpUrl(rpcUrl)) {
328
351
  throw new Error(
329
- `Solana RPC unavailable while fetching a recent blockhash. Retry or configure a different RPC endpoint. ${String(err.message ?? err)}`,
330
- { cause: err }
352
+ 'Invalid Solana RPC URL: expected a full http:// or https:// URL. Check NANSEN_SOLANA_RPC.'
331
353
  );
332
354
  }
333
355
 
334
- if (!response.ok) {
335
- const text = await response.text().catch(() => '');
336
- throw new Error(
337
- `Solana RPC returned HTTP ${response.status} while fetching a recent blockhash. Retry or configure a different RPC endpoint. ${text.slice(0, 100)}`
338
- );
339
- }
356
+ const controller = new AbortController();
357
+ const timer = setTimeout(() => controller.abort(), SOLANA_RPC_TIMEOUT_MS);
358
+ const timeoutError = (cause) => new Error(
359
+ `Solana RPC did not respond within ${SOLANA_RPC_TIMEOUT_MS / 1000}s while fetching a recent blockhash. Retry or configure a different RPC endpoint.`,
360
+ { cause }
361
+ );
340
362
 
341
- let data;
342
363
  try {
343
- data = await response.json();
344
- } catch {
345
- throw new Error(
346
- 'Solana RPC returned an invalid response while fetching a recent blockhash. Retry or configure a different RPC endpoint.'
347
- );
348
- }
364
+ let response;
365
+ try {
366
+ response = await fetch(rpcUrl, {
367
+ method: 'POST',
368
+ headers: { 'Content-Type': 'application/json' },
369
+ body: JSON.stringify({
370
+ jsonrpc: '2.0',
371
+ id: 1,
372
+ method: 'getLatestBlockhash',
373
+ params: [{ commitment: 'finalized' }],
374
+ }),
375
+ signal: controller.signal,
376
+ });
377
+ } catch (err) {
378
+ if (controller.signal.aborted) throw timeoutError(err);
379
+ throw new Error(
380
+ `Solana RPC unavailable while fetching a recent blockhash. Retry or configure a different RPC endpoint. ${String(err.message ?? err)}`,
381
+ { cause: err }
382
+ );
383
+ }
349
384
 
350
- if (data?.error) {
351
- const detail =
352
- data.error.message != null ? String(data.error.message)
353
- : data.error.code != null ? String(data.error.code)
354
- : 'unknown RPC error';
355
- throw new Error(
356
- `Solana RPC failed while fetching a recent blockhash: ${detail}. Retry or configure a different RPC endpoint.`
357
- );
358
- }
385
+ if (!response.ok) {
386
+ const text = await response.text().catch(() => '');
387
+ throw new Error(
388
+ `Solana RPC returned HTTP ${response.status} while fetching a recent blockhash. Retry or configure a different RPC endpoint. ${text.slice(0, 100)}`
389
+ );
390
+ }
359
391
 
360
- const blockhash = data?.result?.value?.blockhash;
361
- if (typeof blockhash !== 'string' || blockhash.length === 0) {
362
- throw new Error(
363
- 'Solana RPC returned no recent blockhash. Retry or configure a different RPC endpoint.'
364
- );
365
- }
392
+ let data;
393
+ try {
394
+ data = await response.json();
395
+ } catch (err) {
396
+ if (controller.signal.aborted) throw timeoutError(err);
397
+ throw new Error(
398
+ 'Solana RPC returned an invalid response while fetching a recent blockhash. Retry or configure a different RPC endpoint.',
399
+ { cause: err }
400
+ );
401
+ }
366
402
 
367
- return blockhash;
403
+ if (data?.error) {
404
+ const detail =
405
+ data.error.message != null ? String(data.error.message)
406
+ : data.error.code != null ? String(data.error.code)
407
+ : 'unknown RPC error';
408
+ throw new Error(
409
+ `Solana RPC failed while fetching a recent blockhash: ${detail}. Retry or configure a different RPC endpoint.`
410
+ );
411
+ }
412
+
413
+ const blockhash = data?.result?.value?.blockhash;
414
+ if (typeof blockhash !== 'string' || blockhash.length === 0) {
415
+ throw new Error(
416
+ 'Solana RPC returned no recent blockhash. Retry or configure a different RPC endpoint.'
417
+ );
418
+ }
419
+
420
+ return blockhash;
421
+ } finally {
422
+ clearTimeout(timer);
423
+ }
368
424
  }
369
425
 
370
426
  /**
371
427
  * Get RPC URL for a Solana network identifier.
372
428
  */
373
429
  export function getSolanaRpcUrl(network) {
374
- if (network === SOLANA_MAINNET_NETWORK) return 'https://api.mainnet-beta.solana.com';
430
+ // Mainnet goes through the shared registry so NANSEN_SOLANA_RPC applies to
431
+ // x402 blockhash and balance calls the same way it does to every other
432
+ // Solana path (transfer, trading, limit orders). The default is unchanged.
433
+ if (network === SOLANA_MAINNET_NETWORK) return CHAIN_RPCS.solana;
375
434
  // Devnet/testnet resolve for tooling (e.g. balance checks), but the x402 pay
376
435
  // path never reaches them: SVM_X402_TOKENS is mainnet-only, so the policy layer
377
436
  // refuses a devnet/testnet requirement before signing. Adding a non-mainnet
package/src/x402.js CHANGED
@@ -42,20 +42,37 @@ export function parsePaymentRequirements(response) {
42
42
  }
43
43
 
44
44
  /**
45
- * Rank payment requirements. Prefers EVM (gasless) over Solana.
46
- * Returns all supported requirements in priority order.
45
+ * Rank payment requirements cheapest first.
46
+ *
47
+ * A 402 response may offer several options that are all individually valid
48
+ * and within the per-payment cap. The caller signs them in this order and
49
+ * stops at the first the server accepts, so the order decides what the wallet
50
+ * pays: server order alone let a merchant list an expensive option first and
51
+ * be paid it while a cheaper one for the same resource sat in the same
52
+ * response.
53
+ *
54
+ * Price comes from evaluatePaymentRequirement, the same function that later
55
+ * guards the payment, so ranking and policy cannot disagree. An option the
56
+ * policy refuses sorts last rather than being dropped here: the caller logs
57
+ * its reason when it tries and skips it.
58
+ *
59
+ * Ties keep the previous behaviour — EVM before Solana, then the server's own
60
+ * order — so a response whose options cost the same is unaffected.
47
61
  */
48
62
  function rankRequirements(requirements) {
49
- const ranked = [];
50
- // EVM first (gasless for client)
51
- for (const r of requirements) {
52
- if (isEvmNetwork(r.network)) ranked.push(r);
53
- }
54
- // Then Solana
55
- for (const r of requirements) {
56
- if (isSvmNetwork(r.network)) ranked.push(r);
57
- }
58
- return ranked;
63
+ return requirements
64
+ .filter(r => isEvmNetwork(r.network) || isSvmNetwork(r.network))
65
+ .map((requirement, index) => {
66
+ const decision = evaluatePaymentRequirement(requirement);
67
+ return {
68
+ requirement,
69
+ index,
70
+ rail: isEvmNetwork(requirement.network) ? 0 : 1,
71
+ usd: decision.ok && Number.isFinite(decision.usd) ? decision.usd : Number.POSITIVE_INFINITY,
72
+ };
73
+ })
74
+ .sort((a, b) => (a.usd - b.usd) || (a.rail - b.rail) || (a.index - b.index))
75
+ .map(entry => entry.requirement);
59
76
  }
60
77
 
61
78
  // ERC-20 allowance(owner, spender) selector for the Permit2 preflight.
@@ -103,6 +120,18 @@ async function buildPaymentForRequirement(requirement, exported, url) {
103
120
  return null;
104
121
  }
105
122
 
123
+ // exportWallet returns a null key for a chain the wallet file doesn't hold.
124
+ // Skip that option with a clear reason instead of failing on the missing key.
125
+ const rail = isEvmNetwork(requirement.network) ? 'evm' : 'solana';
126
+ if (!exported[rail]?.privateKey || !exported[rail]?.address) {
127
+ const chain = rail === 'evm' ? 'EVM' : 'Solana';
128
+ console.error(
129
+ `[x402] Skipping ${requirement.network} option: wallet "${exported.name}" has no ${chain} key. ` +
130
+ 'Create a wallet with both keys (nansen wallet create) and make it the default (nansen wallet default <name>).',
131
+ );
132
+ return null;
133
+ }
134
+
106
135
  if (isEvmNetwork(requirement.network)) {
107
136
  if ((requirement.extra || {}).assetTransferMethod === 'permit2-exact') {
108
137
  const resolvedAmount = resolvePaymentAmount(requirement);
@@ -194,8 +223,11 @@ export async function* createPaymentSignatures(response, url, options = {}) {
194
223
  try {
195
224
  const sig = await buildPaymentForRequirement(req, exported, url);
196
225
  if (sig) yield { signature: sig, network: req.network, asset: req.asset };
197
- } catch {
198
- // This payment option failed to build, try next
226
+ } catch (err) {
227
+ // This payment option failed to build; say why and try the next one
228
+ // (otherwise a malformed server option only surfaces as a generic
229
+ // payment failure once every option is exhausted).
230
+ console.error(`[x402] Skipping ${req.network} option: ${err?.message || err}`);
199
231
  continue;
200
232
  }
201
233
  }