nansen-cli 2.2.0 → 2.4.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 (78) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +109 -33
  3. package/docs/auth.md +56 -0
  4. package/docs/browser-login.md +101 -7
  5. package/docs/error-codes.md +249 -0
  6. package/package.json +10 -4
  7. package/skills/nansen-agent-guide/SKILL.md +54 -1
  8. package/skills/nansen-alerts-webhook-listener/SKILL.md +1 -1
  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 +1 -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 +2 -1
  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 +1 -1
  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 +1 -1
  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 +336 -121
  43. package/src/auth-credentials.js +1 -0
  44. package/src/auth-state.js +2 -2
  45. package/src/auth-store-native.js +6 -1
  46. package/src/auth-store-worker.js +1 -1
  47. package/src/auth-store.js +9 -4
  48. package/src/bridge.js +19 -10
  49. package/src/cli.js +258 -107
  50. package/src/commands/agent.js +2 -3
  51. package/src/commands/alerts.js +277 -9
  52. package/src/commands/completion.js +6 -1
  53. package/src/commands/feedback.js +413 -0
  54. package/src/commands/mcp.js +1 -1
  55. package/src/commands/research.js +14 -37
  56. package/src/cost-cache.js +33 -7
  57. package/src/doctor.js +14 -5
  58. package/src/error-codes.js +226 -0
  59. package/src/feedback-journal.js +86 -0
  60. package/src/input-validation.js +551 -0
  61. package/src/limit-order.js +12 -3
  62. package/src/perp.js +2 -1
  63. package/src/privy.js +144 -48
  64. package/src/query-options.js +30 -7
  65. package/src/rpc-urls.js +3 -1
  66. package/src/schema.json +1254 -150
  67. package/src/solana-tx.js +4 -0
  68. package/src/telemetry.js +5 -1
  69. package/src/trade-validation.js +190 -21
  70. package/src/trading.js +229 -129
  71. package/src/transfer.js +7 -1
  72. package/src/update-check.js +32 -5
  73. package/src/wallet.js +220 -57
  74. package/src/walletconnect-x402.js +152 -52
  75. package/src/x402-audit.js +191 -0
  76. package/src/x402-payment-balance.js +90 -0
  77. package/src/x402-policy.js +151 -4
  78. package/src/x402.js +51 -22
package/src/transfer.js CHANGED
@@ -664,7 +664,7 @@ export { parseAmount, formatAmount, signEd25519, encodeCompactU16, base58Decode,
664
664
  * Solana builds unsigned tx, signs via Privy, then broadcasts.
665
665
  */
666
666
  async function sendTokensViaPrivy({ to, amount, chain, token, max, dryRun, walletInfo }) {
667
- const { PrivyClient } = await import('./privy.js');
667
+ const { PrivyClient, assertPrivyWalletAddress } = await import('./privy.js');
668
668
  const client = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
669
669
 
670
670
  if (chain === 'solana') {
@@ -672,6 +672,9 @@ async function sendTokensViaPrivy({ to, amount, chain, token, max, dryRun, walle
672
672
  const fromAddress = walletInfo.solana;
673
673
  if (!fromAddress) throw new Error('No Solana wallet in this Privy wallet');
674
674
  if (!walletId) throw new Error('No Privy Solana wallet ID found. Re-create the wallet with: nansen wallet create --provider privy');
675
+ if (token && !validateSolanaAddress(token).valid) throw new Error('Invalid Solana token address');
676
+ if (!max && !token) parseAmount(amount, 9);
677
+ await assertPrivyWalletAddress(client, walletId, fromAddress, 'solana');
675
678
 
676
679
  if (max && !token) {
677
680
  const balResult = await rpcCall(CHAIN_RPCS.solana, 'getBalance', [fromAddress, { commitment: 'confirmed' }]);
@@ -715,6 +718,9 @@ async function sendTokensViaPrivy({ to, amount, chain, token, max, dryRun, walle
715
718
 
716
719
  const chainId = CHAIN_IDS[chain];
717
720
  if (!chainId) throw new Error(`Unsupported chain: ${chain}`);
721
+ if (token && !validateEvmAddress(token).valid) throw new Error('Invalid ERC-20 token address');
722
+ if (!max && !token) parseAmount(amount, 18);
723
+ await assertPrivyWalletAddress(client, walletId, fromAddress, 'evm');
718
724
 
719
725
  let decimals = 18;
720
726
  const rpcUrl = CHAIN_RPCS[chain] || CHAIN_RPCS.evm;
@@ -44,7 +44,27 @@ export function isNewer(latest, current) {
44
44
  return compareSemver(latest, current) > 0;
45
45
  }
46
46
 
47
- const LAST_VERSION_FILE = path.join(CONFIG_DIR, 'last-version.json');
47
+ /**
48
+ * Return the minimum Node version the latest release requires when the
49
+ * running Node is below it, otherwise null. `enginesNode` is the cached
50
+ * `engines.node` of the latest release; a cache written before it was
51
+ * recorded has none, so this returns null and callers fall back to the plain
52
+ * update notice.
53
+ *
54
+ * Only a single lower bound (">=22", ">=22.14.0") is understood, compared on
55
+ * the full version so ">=22.14.0" rejects v22.0.0. Any other range ("||", "^",
56
+ * upper bounds) also returns null rather than guessing.
57
+ *
58
+ * npm installs the newest version whose engines match the running Node, so on
59
+ * an older Node "npm i -g nansen-cli" resolves back to the installed version.
60
+ */
61
+ export function nodeTooOldFor(enginesNode, nodeVersion = process.version) {
62
+ const match = /^\s*>=\s*v?(\d+(?:\.\d+){0,2})\s*$/.exec(typeof enginesNode === 'string' ? enginesNode : '');
63
+ if (!match || !/^v?\d/.test(String(nodeVersion))) return null;
64
+ return compareSemver(nodeVersion, match[1]) < 0 ? match[1] : null;
65
+ }
66
+
67
+ const LAST_VERSION_FILE =path.join(CONFIG_DIR, 'last-version.json');
48
68
 
49
69
  /**
50
70
  * After an update, show a one-time "what's new" notice on the first run.
@@ -82,16 +102,20 @@ export function getUpgradeNotice(currentVersion) {
82
102
  /**
83
103
  * Read the cached check result and return a notification string (or null).
84
104
  */
85
- export function getUpdateNotification(currentVersion) {
105
+ export function getUpdateNotification(currentVersion, nodeVersion = process.version) {
86
106
  try {
87
107
  if (process.env.NO_UPDATE_NOTIFIER || process.env.CI) return null;
88
108
  if (!fs.existsSync(CACHE_FILE)) return null;
89
109
 
90
110
  const raw = fs.readFileSync(CACHE_FILE, 'utf8');
91
- const { latest } = JSON.parse(raw);
111
+ const { latest, engines } = JSON.parse(raw);
92
112
  if (!latest) return null;
93
113
 
94
114
  if (isNewer(latest, currentVersion)) {
115
+ const neededNode = nodeTooOldFor(engines, nodeVersion);
116
+ if (neededNode) {
117
+ return `Update available: ${currentVersion} → ${latest}, but it requires Node >= ${neededNode} (you have ${nodeVersion}). Install Node >= ${neededNode}, then: npm i -g ${PACKAGE_NAME}`;
118
+ }
95
119
  return `Update available: ${currentVersion} → ${latest} (npm i -g ${PACKAGE_NAME})`;
96
120
  }
97
121
  return null;
@@ -129,12 +153,15 @@ export function buildCheckScript(dir, file, url = REGISTRY_URL) {
129
153
  res.on('data', c => body += c);
130
154
  res.on('end', () => {
131
155
  try {
132
- const { version } = JSON.parse(body);
156
+ const { version, engines } = JSON.parse(body);
133
157
  if (typeof version !== 'string' || version.trim() === '') return;
158
+ // Keep the latest release's Node requirement so the notice can say
159
+ // when a reinstall would not reach it. Omitted when absent.
160
+ const node = engines && typeof engines.node === 'string' ? engines.node : undefined;
134
161
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { mode: 0o700, recursive: true });
135
162
  const tmp = file + '.' + process.pid + '.tmp';
136
163
  try {
137
- fs.writeFileSync(tmp, JSON.stringify({ latest: version, checkedAt: Date.now() }));
164
+ fs.writeFileSync(tmp, JSON.stringify({ latest: version, engines: node, checkedAt: Date.now() }));
138
165
  fs.renameSync(tmp, file);
139
166
  } catch (e) {
140
167
  try { fs.unlinkSync(tmp); } catch {}
package/src/wallet.js CHANGED
@@ -6,6 +6,7 @@
6
6
  import { rejectBlankOption } from './query-options.js';
7
7
  import crypto from 'crypto';
8
8
  import fs from 'fs';
9
+ import os from 'os';
9
10
  import path from 'path';
10
11
  import * as readline from 'readline';
11
12
  import { base58 } from '@scure/base';
@@ -313,6 +314,144 @@ function saveWalletConfig(config) {
313
314
  writeWalletJsonAtomic(getWalletConfigPath(), config);
314
315
  }
315
316
 
317
+ // ============= Wallet Mutation Lock =============
318
+
319
+ // Each JSON write above is atomic, but a mutation is a read-check-write across
320
+ // config.json and the wallet files. Two overlapping `wallet create` runs could
321
+ // both see an empty config, both set their own passwordHash, and the last
322
+ // writer would strand the other wallet. Every mutation therefore runs under
323
+ // one lock directory (mkdir is atomic on every platform).
324
+ //
325
+ // The owner is recorded with this machine's hostname and PID. A lock is
326
+ // cleared automatically only when its owner on this machine no longer exists
327
+ // (a crash, or Ctrl-C, which skips the release). Any other lock (owner still
328
+ // running, owner not recorded or unreadable, owner on another machine) is
329
+ // left alone, however old, since a suspended or slow holder would otherwise
330
+ // write over its successor; the busy error tells the user to delete it. The
331
+ // trade-offs: a crashed holder whose PID is reused by an unrelated process, a
332
+ // crash between creating the lock and recording its owner, and a lock taken
333
+ // from another machine sharing this directory (not supported) all need the
334
+ // lock deleted by hand.
335
+ const WALLET_LOCK_NAME = '.wallet.lock';
336
+ const WALLET_LOCK_WAIT_MS = 30_000;
337
+ const WALLET_LOCK_POLL_MS = 25;
338
+ const lockSleepCell = new Int32Array(new SharedArrayBuffer(4));
339
+
340
+ function newLockToken() {
341
+ return `${os.hostname()}\n${process.pid}\n${crypto.randomBytes(16).toString('hex')}`;
342
+ }
343
+
344
+ // Records the owner token in a lock directory this process just created; on
345
+ // failure removes the directory so it is not left without an owner.
346
+ function writeLockOwner(dirPath, token) {
347
+ try {
348
+ fs.chmodSync(dirPath, 0o700); // mkdir's mode is filtered through the umask
349
+ fs.writeFileSync(path.join(dirPath, 'owner'), token, { mode: 0o600 });
350
+ } catch (err) {
351
+ fs.rmSync(dirPath, { recursive: true, force: true });
352
+ throw err;
353
+ }
354
+ }
355
+
356
+ function readLockToken(lockPath) {
357
+ try { return fs.readFileSync(path.join(lockPath, 'owner'), 'utf8'); } catch { return null; }
358
+ }
359
+
360
+ // The owner token is "<hostname>\n<pid>\n<random>". Returns { pid, alive }
361
+ // for an owner on this machine, or null when the owner cannot be checked.
362
+ function lockOwner(lockPath) {
363
+ const [host, pid] = (readLockToken(lockPath) || '').split('\n');
364
+ if (host !== os.hostname() || !/^\d+$/.test(pid || '')) return null;
365
+ try {
366
+ process.kill(Number(pid), 0);
367
+ return { pid, alive: true };
368
+ } catch (err) {
369
+ if (err.code === 'ESRCH') return { pid, alive: false };
370
+ if (err.code === 'EPERM') return { pid, alive: true };
371
+ return null;
372
+ }
373
+ }
374
+
375
+ function lockAbandoned(lockPath) {
376
+ return lockOwner(lockPath)?.alive === false;
377
+ }
378
+
379
+ // Moves an abandoned lock aside and deletes it. Only one process clears a
380
+ // lock at a time (the .break directory, which records its owner the same
381
+ // way), and it re-checks the lock while holding that, so it can never move
382
+ // aside a fresh lock another process took after an earlier clear. A .break
383
+ // left by a crashed clearer on this machine is removed by the same rule.
384
+ function breakStaleWalletLock(lockPath) {
385
+ if (!lockAbandoned(lockPath)) return;
386
+ const breakPath = `${lockPath}.break`;
387
+ try {
388
+ fs.mkdirSync(breakPath, { mode: 0o700 });
389
+ } catch (err) {
390
+ if (err.code === 'EEXIST' && lockAbandoned(breakPath)) {
391
+ fs.rmSync(breakPath, { recursive: true, force: true });
392
+ }
393
+ return;
394
+ }
395
+ writeLockOwner(breakPath, newLockToken());
396
+ try {
397
+ if (!lockAbandoned(lockPath)) return;
398
+ const aside = `${lockPath}.stale-${process.pid}-${crypto.randomBytes(4).toString('hex')}`;
399
+ try { fs.renameSync(lockPath, aside); } catch { return; }
400
+ fs.rmSync(aside, { recursive: true, force: true });
401
+ } finally {
402
+ fs.rmSync(breakPath, { recursive: true, force: true });
403
+ }
404
+ }
405
+
406
+ /**
407
+ * Run fn() while holding the wallet mutation lock. fn must be synchronous:
408
+ * never hold the lock across a network call. The options exist for tests.
409
+ */
410
+ export function withWalletLock(fn, { waitMs = WALLET_LOCK_WAIT_MS } = {}) {
411
+ ensureWalletsDir();
412
+ const lockPath = assertWalletsDirPath(path.join(getWalletsDir(), WALLET_LOCK_NAME));
413
+ const token = newLockToken();
414
+ const deadline = Date.now() + waitMs;
415
+ for (;;) {
416
+ try {
417
+ fs.mkdirSync(lockPath, { mode: 0o700 });
418
+ break;
419
+ } catch (err) {
420
+ // Windows reports EPERM for a lock directory that is still being
421
+ // deleted; any other EPERM is a real permission error.
422
+ const busy = err.code === 'EEXIST'
423
+ || (process.platform === 'win32' && err.code === 'EPERM' && fs.existsSync(lockPath));
424
+ if (!busy) throw err;
425
+ }
426
+ breakStaleWalletLock(lockPath);
427
+ if (Date.now() > deadline) {
428
+ const owner = lockOwner(lockPath);
429
+ if (owner?.alive) {
430
+ throw new Error(`Another nansen wallet command (PID ${owner.pid}) is still running. Retry when it finishes. If no such command is running, delete ${lockPath}`);
431
+ }
432
+ throw new Error(`Another nansen wallet command is still running. Retry in a few seconds. If none is running, delete ${lockPath}`);
433
+ }
434
+ Atomics.wait(lockSleepCell, 0, 0, WALLET_LOCK_POLL_MS);
435
+ }
436
+ writeLockOwner(lockPath, token);
437
+ try {
438
+ return fn();
439
+ } finally {
440
+ // Move the lock aside first: the rename is atomic, so the lock whose
441
+ // token is checked is the one removed. Nothing clears a lock whose owner
442
+ // is still running, so it is ours; if not, put it back (or leave it
443
+ // aside) rather than delete another owner's lock.
444
+ const aside = `${lockPath}.release-${process.pid}-${crypto.randomBytes(4).toString('hex')}`;
445
+ let moved = false;
446
+ try { fs.renameSync(lockPath, aside); moved = true; } catch { /* gone: nothing to release */ }
447
+ if (moved && readLockToken(aside) === token) {
448
+ fs.rmSync(aside, { recursive: true, force: true });
449
+ } else if (moved) {
450
+ try { fs.renameSync(aside, lockPath); } catch { /* leave it aside */ }
451
+ }
452
+ }
453
+ }
454
+
316
455
  const WALLET_NAME_RE = /^[a-zA-Z0-9_-]{1,64}$/;
317
456
 
318
457
  function validateWalletName(name) {
@@ -494,12 +633,33 @@ export function listWallets() {
494
633
  }
495
634
 
496
635
  /**
497
- * Create a new wallet pair (EVM + Solana).
636
+ * Create a new wallet pair (EVM + Solana). beforeCommit runs inside the
637
+ * wallet lock once every check has passed and before anything is written;
638
+ * the CLI saves the password there so a racing create can't overwrite it.
498
639
  */
499
- export function createWallet(name, password) {
500
- ensureWalletsDir();
501
- const config = getWalletConfig();
640
+ export function createWallet(name, password, { beforeCommit } = {}) {
502
641
  const walletFile = getWalletFile(name);
642
+ // Key generation and encryption (two scrypt runs) need no shared state, so
643
+ // they run before the lock to keep it short.
644
+ const evm = generateEvmWallet();
645
+ const solana = generateSolanaWallet();
646
+ const wallet = {
647
+ name,
648
+ createdAt: new Date().toISOString(),
649
+ evm: {
650
+ address: evm.address,
651
+ encrypted: encryptKey(evm.privateKey, password),
652
+ },
653
+ solana: {
654
+ address: solana.address,
655
+ encrypted: encryptKey(solana.privateKey, password),
656
+ },
657
+ };
658
+ return withWalletLock(() => createWalletLocked(name, password, walletFile, wallet, beforeCommit));
659
+ }
660
+
661
+ function createWalletLocked(name, password, walletFile, wallet, beforeCommit) {
662
+ const config = getWalletConfig();
503
663
 
504
664
  if (fs.existsSync(walletFile)) {
505
665
  throw new Error(`Wallet "${name}" already exists`);
@@ -529,25 +689,11 @@ export function createWallet(name, password) {
529
689
  }
530
690
  config.passwordHash = hashPassword(password);
531
691
  } else if (!verifyPassword(password, config)) {
532
- throw new Error('Incorrect password');
692
+ throw new CommandError('Incorrect password — does not match existing wallets.', 'INCORRECT_PASSWORD');
533
693
  }
534
694
  }
535
695
 
536
- const evm = generateEvmWallet();
537
- const solana = generateSolanaWallet();
538
-
539
- const wallet = {
540
- name,
541
- createdAt: new Date().toISOString(),
542
- evm: {
543
- address: evm.address,
544
- encrypted: encryptKey(evm.privateKey, password),
545
- },
546
- solana: {
547
- address: solana.address,
548
- encrypted: encryptKey(solana.privateKey, password),
549
- },
550
- };
696
+ beforeCommit?.();
551
697
 
552
698
  writeWalletJsonAtomic(walletFile, wallet);
553
699
 
@@ -559,8 +705,8 @@ export function createWallet(name, password) {
559
705
 
560
706
  return {
561
707
  name,
562
- evm: evm.address,
563
- solana: solana.address,
708
+ evm: wallet.evm.address,
709
+ solana: wallet.solana.address,
564
710
  isDefault: config.defaultWallet === name,
565
711
  };
566
712
  }
@@ -624,6 +770,11 @@ export function exportWallet(name, password) {
624
770
  * Set the default wallet.
625
771
  */
626
772
  export function setDefaultWallet(name) {
773
+ requireWalletFile(name); // re-checked under the lock
774
+ return withWalletLock(() => setDefaultWalletLocked(name));
775
+ }
776
+
777
+ function setDefaultWalletLocked(name) {
627
778
  requireWalletFile(name);
628
779
 
629
780
  const config = getWalletConfig();
@@ -637,6 +788,11 @@ export function setDefaultWallet(name) {
637
788
  * Delete a wallet.
638
789
  */
639
790
  export async function deleteWallet(name, password) {
791
+ requireWalletFile(name); // re-checked under the lock
792
+ return withWalletLock(() => deleteWalletLocked(name, password));
793
+ }
794
+
795
+ function deleteWalletLocked(name, password) {
640
796
  const walletFile = requireWalletFile(name);
641
797
 
642
798
  const data = readWalletJson(walletFile);
@@ -776,22 +932,15 @@ export function buildWalletCommands(deps = {}) {
776
932
  }
777
933
  }
778
934
 
779
- // Verify password matches existing wallets BEFORE touching keychain
780
- if (password !== null) {
781
- const config = getWalletConfig();
782
- if (config.passwordHash && !verifyPassword(password, config)) {
783
- throw new CommandError('❌ Incorrect password — does not match existing wallets.', 'INCORRECT_PASSWORD');
784
- }
785
- }
786
-
787
- // Persist password BEFORE creating wallet so we know the storage situation
935
+ // Persist the password before the wallet is written, so we know the
936
+ // storage situation, but inside the wallet lock: a racing create
937
+ // must not overwrite it, nor a racing delete of the last wallet
938
+ // remove it.
788
939
  let storageResult = { stored: false, method: 'none' };
789
- if (password !== null) {
790
- storageResult = storePassword(password);
791
- }
940
+ const beforeCommit = password === null ? undefined : () => { storageResult = storePassword(password); };
792
941
 
793
942
  try {
794
- const result = createWallet(name, password);
943
+ const result = createWallet(name, password, { beforeCommit });
795
944
  log(`\n✓ Wallet "${result.name}" created\n`);
796
945
  log(` EVM: ${result.evm}`);
797
946
  log(` Solana: ${result.solana}`);
@@ -825,7 +974,7 @@ export function buildWalletCommands(deps = {}) {
825
974
  log('');
826
975
  return;
827
976
  } catch (err) {
828
- throw new CommandError(`❌ ${err.message}`, 'CREATE_FAILED');
977
+ throw new CommandError(`❌ ${err.message}`, err.code === 'INCORRECT_PASSWORD' ? 'INCORRECT_PASSWORD' : 'CREATE_FAILED');
829
978
  }
830
979
  },
831
980
 
@@ -1129,7 +1278,7 @@ export function buildWalletCommands(deps = {}) {
1129
1278
  },
1130
1279
 
1131
1280
  'forget-password': async () => {
1132
- const result = deletePassword();
1281
+ const result = withWalletLock(() => deletePassword());
1133
1282
  if (result.keychain || result.file) {
1134
1283
  log('✓ Password removed from:');
1135
1284
  if (result.keychain) log(' - System keychain');
@@ -1157,28 +1306,33 @@ export function buildWalletCommands(deps = {}) {
1157
1306
  return;
1158
1307
  }
1159
1308
 
1160
- // Verify password actually decrypts wallets before overwriting keychain
1161
- const walletConfig = getWalletConfig();
1162
- if (walletConfig.passwordHash && !verifyPassword(password, walletConfig)) {
1163
- const resolution = source === 'file'
1164
- ? [
1165
- 'The password in ~/.nansen/wallets/.credentials is incorrect.',
1166
- 'Run: nansen wallet forget-password then re-run with the correct password: NANSEN_WALLET_PASSWORD=<pw> nansen wallet secure',
1167
- ]
1168
- : [
1169
- 'Unset NANSEN_WALLET_PASSWORD if it is stale, then re-run: nansen wallet secure',
1170
- ];
1171
- throw new CommandError(`Password from '${source}' does not match the wallet's stored hash.`, 'INCORRECT_PASSWORD', {
1172
- error: 'INCORRECT_PASSWORD',
1173
- message: `Password from '${source}' does not match the wallet's stored hash.`,
1174
- resolution,
1175
- });
1176
- }
1309
+ // Verify and store under the wallet lock, so a racing first create
1310
+ // can't set a different password in between.
1311
+ const { stored, method, fileRemoved } = withWalletLock(() => {
1312
+ // Verify password actually decrypts wallets before overwriting keychain
1313
+ const walletConfig = getWalletConfig();
1314
+ if (walletConfig.passwordHash && !verifyPassword(password, walletConfig)) {
1315
+ const resolution = source === 'file'
1316
+ ? [
1317
+ 'The password in ~/.nansen/wallets/.credentials is incorrect.',
1318
+ 'Run: nansen wallet forget-password then re-run with the correct password: NANSEN_WALLET_PASSWORD=<pw> nansen wallet secure',
1319
+ ]
1320
+ : [
1321
+ 'Unset NANSEN_WALLET_PASSWORD if it is stale, then re-run: nansen wallet secure',
1322
+ ];
1323
+ throw new CommandError(`Password from '${source}' does not match the wallet's stored hash.`, 'INCORRECT_PASSWORD', {
1324
+ error: 'INCORRECT_PASSWORD',
1325
+ message: `Password from '${source}' does not match the wallet's stored hash.`,
1326
+ resolution,
1327
+ });
1328
+ }
1177
1329
 
1178
- // Try to migrate to keychain
1179
- const { stored, method } = storePassword(password);
1330
+ // Try to migrate to keychain
1331
+ const result = storePassword(password);
1332
+ const migrated = result.stored && result.method === 'keychain';
1333
+ return { ...result, fileRemoved: migrated && deleteCredentialsFile() };
1334
+ });
1180
1335
  if (stored && method === 'keychain') {
1181
- const fileRemoved = deleteCredentialsFile();
1182
1336
  const fromLabel = source === 'file'
1183
1337
  ? '~/.nansen/wallets/.credentials file'
1184
1338
  : 'NANSEN_WALLET_PASSWORD env var';
@@ -1253,8 +1407,17 @@ ENVIRONMENT:
1253
1407
  NANSEN_BASE_RPC Custom Base RPC endpoint
1254
1408
  NANSEN_SOLANA_RPC Custom Solana RPC endpoint
1255
1409
  NANSEN_X402_MAX_AMOUNT Max USD per x402 auto-payment (default 1.00; "unlimited" to disable)
1410
+ NANSEN_X402_SESSION_MAX_AMOUNT
1411
+ Max total USD of x402 auto-payments one CLI process signs and the
1412
+ server doesn't cleanly reject (unset or "unlimited" = no limit; an
1413
+ invalid value refuses every payment; environment only). It resets
1414
+ with every process, so it does not limit spending across separate runs.
1256
1415
  NANSEN_X402_ALLOWED_PAYTO Comma-separated recipient allowlist for x402 auto-payment (optional)
1257
1416
 
1417
+ x402 auto-payments are recorded in ~/.nansen/x402/payments.jsonl (amount, network,
1418
+ asset, recipient, request path and outcome; never signatures, request bodies or
1419
+ query strings).
1420
+
1258
1421
  EXAMPLES:
1259
1422
  NANSEN_WALLET_PASSWORD=mypass nansen wallet create --name trading
1260
1423
  nansen wallet create --name agent-wallet --provider privy