nansen-cli 2.3.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/README.md +61 -38
  3. package/docs/auth.md +56 -0
  4. package/docs/browser-login.md +101 -7
  5. package/docs/error-codes.md +251 -0
  6. package/package.json +10 -4
  7. package/skills/nansen-agent-guide/SKILL.md +20 -4
  8. package/skills/nansen-alerts-webhook-listener/SKILL.md +17 -14
  9. package/skills/nansen-dca-tracker/SKILL.md +1 -1
  10. package/skills/nansen-defi-positions/SKILL.md +1 -1
  11. package/skills/nansen-exit-signals/SKILL.md +2 -2
  12. package/skills/nansen-fund-tracker/SKILL.md +1 -1
  13. package/skills/nansen-general-search/SKILL.md +1 -1
  14. package/skills/nansen-holder-analysis/SKILL.md +2 -2
  15. package/skills/nansen-limit-orders/SKILL.md +9 -1
  16. package/skills/nansen-mpp-payment/SKILL.md +2 -2
  17. package/skills/nansen-perp-screener/SKILL.md +1 -1
  18. package/skills/nansen-perp-trader-profile/SKILL.md +1 -1
  19. package/skills/nansen-polymarket-deep-dive/SKILL.md +1 -1
  20. package/skills/nansen-polymarket-insider-scan/SKILL.md +1 -1
  21. package/skills/nansen-polymarket-trader-profile/SKILL.md +1 -1
  22. package/skills/nansen-portfolio-tracker/SKILL.md +1 -1
  23. package/skills/nansen-prediction-markets/SKILL.md +1 -1
  24. package/skills/nansen-sm-cross-chain-flows/SKILL.md +1 -1
  25. package/skills/nansen-smart-alerts/SKILL.md +5 -2
  26. package/skills/nansen-smart-money-alpha/SKILL.md +1 -1
  27. package/skills/nansen-smart-money-tracker/SKILL.md +8 -7
  28. package/skills/nansen-smart-money-trend/SKILL.md +1 -1
  29. package/skills/nansen-token-research/SKILL.md +1 -1
  30. package/skills/nansen-token-screener/SKILL.md +1 -1
  31. package/skills/nansen-token-transfer-analysis/SKILL.md +1 -1
  32. package/skills/nansen-trading/SKILL.md +23 -2
  33. package/skills/nansen-wallet-batch/SKILL.md +1 -1
  34. package/skills/nansen-wallet-clustering/SKILL.md +1 -1
  35. package/skills/nansen-wallet-deep-dive/SKILL.md +1 -1
  36. package/skills/nansen-wallet-keychain-migration/SKILL.md +1 -1
  37. package/skills/nansen-wallet-manager/SKILL.md +11 -5
  38. package/skills/nansen-wallet-profiler/SKILL.md +1 -1
  39. package/skills/nansen-web-fetcher/SKILL.md +1 -1
  40. package/skills/nansen-web-searcher/SKILL.md +1 -1
  41. package/src/api-endpoints.json +1605 -0
  42. package/src/api.js +282 -124
  43. package/src/auth-credentials.js +1 -0
  44. package/src/auth-key-input.js +57 -9
  45. package/src/auth-state.js +2 -2
  46. package/src/auth-store-native.js +6 -1
  47. package/src/auth-store-worker.js +1 -1
  48. package/src/auth-store.js +9 -4
  49. package/src/auto-paginate.js +25 -7
  50. package/src/bridge.js +19 -10
  51. package/src/cache-inspect.js +16 -6
  52. package/src/cli.js +272 -114
  53. package/src/commands/agent.js +2 -3
  54. package/src/commands/alerts.js +365 -18
  55. package/src/commands/completion.js +4 -1
  56. package/src/commands/feedback.js +98 -37
  57. package/src/commands/mcp.js +1 -1
  58. package/src/commands/research.js +14 -37
  59. package/src/cost-cache.js +33 -7
  60. package/src/doctor.js +14 -5
  61. package/src/ens.js +14 -5
  62. package/src/error-codes.js +228 -0
  63. package/src/execute-guard.js +8 -3
  64. package/src/input-validation.js +555 -0
  65. package/src/limit-order.js +127 -54
  66. package/src/perp.js +358 -35
  67. package/src/privy.js +90 -15
  68. package/src/query-options.js +47 -8
  69. package/src/response-cache-files.js +65 -0
  70. package/src/response-meta.js +8 -2
  71. package/src/rpc-urls.js +3 -1
  72. package/src/schema.json +1254 -156
  73. package/src/solana-tx.js +4 -0
  74. package/src/telemetry-flags.js +75 -0
  75. package/src/trade-validation.js +167 -8
  76. package/src/trading.js +243 -20
  77. package/src/transfer.js +79 -12
  78. package/src/update-check.js +32 -5
  79. package/src/wallet.js +246 -69
  80. package/src/walletconnect-x402.js +27 -9
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,12 +314,159 @@ 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
- function validateWalletName(name) {
457
+ // `wallet send` and limit orders treat these as WalletConnect, so a local
458
+ // wallet with one of these names could never be selected.
459
+ const WALLETCONNECT_NAMES = new Set(['walletconnect', 'wc']);
460
+
461
+ export function validateWalletName(name, { creating = false } = {}) {
319
462
  if (!name || !WALLET_NAME_RE.test(name)) {
320
463
  throw new Error('Wallet name must be 1-64 characters: letters, numbers, hyphens, underscores only');
321
464
  }
465
+ // config.json is the wallet settings file in the same directory. Compared
466
+ // case-insensitively because the macOS and Windows filesystems are.
467
+ if (name.toLowerCase() === 'config' || (creating && WALLETCONNECT_NAMES.has(name))) {
468
+ throw new Error(`"${name}" is a reserved name and cannot be used for a wallet`);
469
+ }
322
470
  }
323
471
 
324
472
  function getWalletFile(name) {
@@ -494,12 +642,34 @@ export function listWallets() {
494
642
  }
495
643
 
496
644
  /**
497
- * Create a new wallet pair (EVM + Solana).
645
+ * Create a new wallet pair (EVM + Solana). beforeCommit runs inside the
646
+ * wallet lock once every check has passed and before anything is written;
647
+ * the CLI saves the password there so a racing create can't overwrite it.
498
648
  */
499
- export function createWallet(name, password) {
500
- ensureWalletsDir();
501
- const config = getWalletConfig();
649
+ export function createWallet(name, password, { beforeCommit } = {}) {
650
+ validateWalletName(name, { creating: true });
502
651
  const walletFile = getWalletFile(name);
652
+ // Key generation and encryption (two scrypt runs) need no shared state, so
653
+ // they run before the lock to keep it short.
654
+ const evm = generateEvmWallet();
655
+ const solana = generateSolanaWallet();
656
+ const wallet = {
657
+ name,
658
+ createdAt: new Date().toISOString(),
659
+ evm: {
660
+ address: evm.address,
661
+ encrypted: encryptKey(evm.privateKey, password),
662
+ },
663
+ solana: {
664
+ address: solana.address,
665
+ encrypted: encryptKey(solana.privateKey, password),
666
+ },
667
+ };
668
+ return withWalletLock(() => createWalletLocked(name, password, walletFile, wallet, beforeCommit));
669
+ }
670
+
671
+ function createWalletLocked(name, password, walletFile, wallet, beforeCommit) {
672
+ const config = getWalletConfig();
503
673
 
504
674
  if (fs.existsSync(walletFile)) {
505
675
  throw new Error(`Wallet "${name}" already exists`);
@@ -529,25 +699,11 @@ export function createWallet(name, password) {
529
699
  }
530
700
  config.passwordHash = hashPassword(password);
531
701
  } else if (!verifyPassword(password, config)) {
532
- throw new Error('Incorrect password');
702
+ throw new CommandError('Incorrect password — does not match existing wallets.', 'INCORRECT_PASSWORD');
533
703
  }
534
704
  }
535
705
 
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
- };
706
+ beforeCommit?.();
551
707
 
552
708
  writeWalletJsonAtomic(walletFile, wallet);
553
709
 
@@ -559,8 +715,8 @@ export function createWallet(name, password) {
559
715
 
560
716
  return {
561
717
  name,
562
- evm: evm.address,
563
- solana: solana.address,
718
+ evm: wallet.evm.address,
719
+ solana: wallet.solana.address,
564
720
  isDefault: config.defaultWallet === name,
565
721
  };
566
722
  }
@@ -624,6 +780,11 @@ export function exportWallet(name, password) {
624
780
  * Set the default wallet.
625
781
  */
626
782
  export function setDefaultWallet(name) {
783
+ requireWalletFile(name); // re-checked under the lock
784
+ return withWalletLock(() => setDefaultWalletLocked(name));
785
+ }
786
+
787
+ function setDefaultWalletLocked(name) {
627
788
  requireWalletFile(name);
628
789
 
629
790
  const config = getWalletConfig();
@@ -637,6 +798,11 @@ export function setDefaultWallet(name) {
637
798
  * Delete a wallet.
638
799
  */
639
800
  export async function deleteWallet(name, password) {
801
+ requireWalletFile(name); // re-checked under the lock
802
+ return withWalletLock(() => deleteWalletLocked(name, password));
803
+ }
804
+
805
+ function deleteWalletLocked(name, password) {
640
806
  const walletFile = requireWalletFile(name);
641
807
 
642
808
  const data = readWalletJson(walletFile);
@@ -776,22 +942,15 @@ export function buildWalletCommands(deps = {}) {
776
942
  }
777
943
  }
778
944
 
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
945
+ // Persist the password before the wallet is written, so we know the
946
+ // storage situation, but inside the wallet lock: a racing create
947
+ // must not overwrite it, nor a racing delete of the last wallet
948
+ // remove it.
788
949
  let storageResult = { stored: false, method: 'none' };
789
- if (password !== null) {
790
- storageResult = storePassword(password);
791
- }
950
+ const beforeCommit = password === null ? undefined : () => { storageResult = storePassword(password); };
792
951
 
793
952
  try {
794
- const result = createWallet(name, password);
953
+ const result = createWallet(name, password, { beforeCommit });
795
954
  log(`\n✓ Wallet "${result.name}" created\n`);
796
955
  log(` EVM: ${result.evm}`);
797
956
  log(` Solana: ${result.solana}`);
@@ -825,7 +984,7 @@ export function buildWalletCommands(deps = {}) {
825
984
  log('');
826
985
  return;
827
986
  } catch (err) {
828
- throw new CommandError(`❌ ${err.message}`, 'CREATE_FAILED');
987
+ throw new CommandError(`❌ ${err.message}`, err.code === 'INCORRECT_PASSWORD' ? 'INCORRECT_PASSWORD' : 'CREATE_FAILED');
829
988
  }
830
989
  },
831
990
 
@@ -1033,7 +1192,7 @@ export function buildWalletCommands(deps = {}) {
1033
1192
  },
1034
1193
 
1035
1194
  'send': async () => {
1036
- rejectBlankOption(options.token, 'token', '<token-address>');
1195
+ rejectBlankOption(options.token, 'token', '<symbol|address>');
1037
1196
  rejectBlankOption(options.wallet, 'wallet', '<name>');
1038
1197
  const { sendTokens } = await import('./transfer.js');
1039
1198
 
@@ -1047,7 +1206,7 @@ export function buildWalletCommands(deps = {}) {
1047
1206
  }
1048
1207
 
1049
1208
  if (!options.chain) {
1050
- throw new CommandError('--chain <evm|solana> is required', 'MISSING_ARGS');
1209
+ throw new CommandError('--chain <evm|ethereum|base|solana> is required', 'MISSING_ARGS');
1051
1210
  }
1052
1211
 
1053
1212
  if (!['evm', 'solana', 'ethereum', 'base'].includes(options.chain)) {
@@ -1103,7 +1262,7 @@ export function buildWalletCommands(deps = {}) {
1103
1262
  log(` From: ${result.from}`);
1104
1263
  log(` To: ${options.to}`);
1105
1264
  log(` Amount: ${result.amount || (isMax ? 'max' : String(options.amount))}`);
1106
- log(` Token: ${options.token || '(native)'}`);
1265
+ log(` Token: ${result.token || '(native)'}`);
1107
1266
  log(` Chain: ${options.chain}`);
1108
1267
  if (result.estimatedFee) log(` Fee: ${result.estimatedFee}`);
1109
1268
  log('');
@@ -1117,7 +1276,7 @@ export function buildWalletCommands(deps = {}) {
1117
1276
  log(` From: ${result.from}`);
1118
1277
  log(` To: ${result.to}`);
1119
1278
  log(` Amount: ${result.amount}`);
1120
- log(` Token: ${result.token}`);
1279
+ log(` Token: ${result.token || '(native)'}`);
1121
1280
  if (result.blockNumber) log(` Block: ${result.blockNumber}`);
1122
1281
  log(` Status: ${result.confirmed ? 'confirmed' : 'pending'}`);
1123
1282
  log(` Explorer: ${result.explorer}`);
@@ -1129,7 +1288,7 @@ export function buildWalletCommands(deps = {}) {
1129
1288
  },
1130
1289
 
1131
1290
  'forget-password': async () => {
1132
- const result = deletePassword();
1291
+ const result = withWalletLock(() => deletePassword());
1133
1292
  if (result.keychain || result.file) {
1134
1293
  log('✓ Password removed from:');
1135
1294
  if (result.keychain) log(' - System keychain');
@@ -1157,28 +1316,33 @@ export function buildWalletCommands(deps = {}) {
1157
1316
  return;
1158
1317
  }
1159
1318
 
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
- }
1319
+ // Verify and store under the wallet lock, so a racing first create
1320
+ // can't set a different password in between.
1321
+ const { stored, method, fileRemoved } = withWalletLock(() => {
1322
+ // Verify password actually decrypts wallets before overwriting keychain
1323
+ const walletConfig = getWalletConfig();
1324
+ if (walletConfig.passwordHash && !verifyPassword(password, walletConfig)) {
1325
+ const resolution = source === 'file'
1326
+ ? [
1327
+ 'The password in ~/.nansen/wallets/.credentials is incorrect.',
1328
+ 'Run: nansen wallet forget-password then re-run with the correct password: NANSEN_WALLET_PASSWORD=<pw> nansen wallet secure',
1329
+ ]
1330
+ : [
1331
+ 'Unset NANSEN_WALLET_PASSWORD if it is stale, then re-run: nansen wallet secure',
1332
+ ];
1333
+ throw new CommandError(`Password from '${source}' does not match the wallet's stored hash.`, 'INCORRECT_PASSWORD', {
1334
+ error: 'INCORRECT_PASSWORD',
1335
+ message: `Password from '${source}' does not match the wallet's stored hash.`,
1336
+ resolution,
1337
+ });
1338
+ }
1177
1339
 
1178
- // Try to migrate to keychain
1179
- const { stored, method } = storePassword(password);
1340
+ // Try to migrate to keychain
1341
+ const result = storePassword(password);
1342
+ const migrated = result.stored && result.method === 'keychain';
1343
+ return { ...result, fileRemoved: migrated && deleteCredentialsFile() };
1344
+ });
1180
1345
  if (stored && method === 'keychain') {
1181
- const fileRemoved = deleteCredentialsFile();
1182
1346
  const fromLabel = source === 'file'
1183
1347
  ? '~/.nansen/wallets/.credentials file'
1184
1348
  : 'NANSEN_WALLET_PASSWORD env var';
@@ -1209,8 +1373,15 @@ USAGE:
1209
1373
  nansen wallet <command> [options]
1210
1374
 
1211
1375
  COMMANDS:
1212
- create [--name <label>] [--provider <local|privy>] [--unsafe-no-password]
1213
- Create a new wallet pair (EVM + Solana)
1376
+ create [--name <label>] [--provider <local|privy>] [--unsafe-no-password] [--human]
1377
+ Create a new wallet pair (EVM + Solana). A local wallet needs a
1378
+ password of at least 12 characters: set NANSEN_WALLET_PASSWORD
1379
+ (a password saved by an earlier create is reused); when neither
1380
+ exists, --human prompts for one. Without one it fails with
1381
+ PASSWORD_REQUIRED (it never prompts on its own). The password is
1382
+ then saved to the OS keychain, or to ~/.nansen/wallets/.credentials
1383
+ (plaintext) when no keychain is available. If neither can be
1384
+ written, keep NANSEN_WALLET_PASSWORD set for later commands
1214
1385
  list List all wallets
1215
1386
  show <name> Show wallet addresses
1216
1387
  export <name> [--reveal | --file <path>]
@@ -1219,10 +1390,11 @@ COMMANDS:
1219
1390
  --file writes them to a new file only you can read (0600)
1220
1391
  default <name> Set the default wallet
1221
1392
  delete <name> Delete a wallet
1222
- send --to <address> --amount <number> --chain <evm|solana> [--token <address>] [--wallet <name>] [--max] [--dry-run]
1393
+ send --to <address> --amount <number> --chain <evm|ethereum|base|solana> [--token <symbol|address>] [--wallet <name>] [--max] [--dry-run]
1223
1394
  Send tokens or native currency (--max sends entire balance, --dry-run previews without sending)
1224
1395
  forget-password Remove saved password from all stores
1225
- secure Migrate password from insecure storage to OS keychain
1396
+ secure Move a password from ~/.nansen/wallets/.credentials or NANSEN_WALLET_PASSWORD
1397
+ into the OS keychain (wallet create already uses the keychain when it can)
1226
1398
 
1227
1399
  OPTIONS:
1228
1400
  --name <label> Wallet name (default: "default")
@@ -1230,19 +1402,23 @@ OPTIONS:
1230
1402
  "privy" creates server-side wallets via Privy API
1231
1403
  --to <address> Recipient address (required for send)
1232
1404
  --amount <number> Amount to send in human-readable format (required unless --max)
1233
- --chain <evm|solana> Blockchain to use (required for send)
1234
- --token <address> Token contract/mint address (optional, sends native if omitted)
1405
+ --chain <chain> Blockchain to use (required for send): evm (Ethereum), ethereum, base, solana
1406
+ --token <symbol|address> Token to send: USDC, USDT, or a token contract/mint address
1407
+ (optional, sends native if omitted)
1235
1408
  --wallet <name> Wallet to use (optional, uses default if omitted; use "walletconnect" or "wc" for WalletConnect, EVM only)
1236
1409
  --max Send entire balance (deducts gas for native transfers)
1237
1410
  --reveal Export: print private keys in plaintext to stdout (explicit acknowledgement)
1238
1411
  --file <path> Export: write private keys to <path> (created 0600, refuses to overwrite)
1239
1412
  --unsafe-no-password Skip encryption — private keys stored UNENCRYPTED on disk (local only)
1240
1413
  --human Enable interactive prompts (for human terminal use only)
1414
+ --dry-run Send: preview the transaction without broadcasting
1241
1415
 
1242
1416
  PASSWORD RESOLUTION (automatic, in order):
1243
1417
  1. NANSEN_WALLET_PASSWORD env var
1244
1418
  2. OS keychain (saved automatically on wallet create)
1245
- 3. Interactive prompt (only with --human flag)
1419
+ 3. ~/.nansen/wallets/.credentials (plaintext fallback, saved on wallet create when no
1420
+ keychain is available; run \`nansen wallet secure\` to move it to the keychain)
1421
+ 4. Interactive prompt (only with --human flag)
1246
1422
 
1247
1423
  ENVIRONMENT:
1248
1424
  NANSEN_WALLET_PASSWORD Wallet encryption password
@@ -1274,6 +1450,7 @@ EXAMPLES:
1274
1450
  nansen wallet default trading
1275
1451
  nansen wallet send --to 0x742d35Cc... --amount 1.5 --chain evm
1276
1452
  nansen wallet send --to 9WzDXw... --amount 0.1 --chain solana --token So11...
1453
+ nansen wallet send --to 0x742d35Cc... --amount 25 --chain base --token USDC
1277
1454
  nansen wallet forget-password
1278
1455
  `);
1279
1456
  return;
@@ -47,6 +47,18 @@ function parseChainId(network) {
47
47
  return match ? Number(match[1]) : null;
48
48
  }
49
49
 
50
+ // The local signer (x402-evm.js) authorizes for an hour; a server-supplied
51
+ // timeout never gets a longer window than that.
52
+ const MAX_PAYMENT_TIMEOUT_SECONDS = 3600;
53
+
54
+ function paymentTimeoutSeconds(maxTimeoutSeconds) {
55
+ const seconds = typeof maxTimeoutSeconds === 'string' && /^\d+$/.test(maxTimeoutSeconds)
56
+ ? Number(maxTimeoutSeconds)
57
+ : maxTimeoutSeconds;
58
+ if (!Number.isSafeInteger(seconds) || seconds <= 0) return 120;
59
+ return Math.min(seconds, MAX_PAYMENT_TIMEOUT_SECONDS);
60
+ }
61
+
50
62
  /**
51
63
  * Build EIP-712 typed data for TransferWithAuthorization (EIP-3009).
52
64
  */
@@ -112,7 +124,7 @@ export function buildEIP712TypedData({ fromAddress, requirement }) {
112
124
  to: payTo,
113
125
  value: amount,
114
126
  validAfter: now - 600, // 10 min in the past to tolerate clock skew between client and verifier
115
- validBefore: now + (maxTimeoutSeconds || 120),
127
+ validBefore: now + paymentTimeoutSeconds(maxTimeoutSeconds),
116
128
  nonce,
117
129
  },
118
130
  };
@@ -139,13 +151,19 @@ export function buildPaymentSignatureHeader({ signature, authorization, resource
139
151
 
140
152
  /**
141
153
  * Format amount for human-readable display (e.g., "0.01 USDC")
154
+ *
155
+ * Prefers the policy decision, which scaled the amount with the known token's
156
+ * decimals; the server's `extra` rarely carries decimals, and the BSC tokens
157
+ * use 18, not 6.
142
158
  */
143
- function formatPaymentAmount(requirement) {
159
+ function formatPaymentAmount(requirement, payment) {
144
160
  const { extra } = requirement;
145
- const rawAmount = resolvePaymentAmount(requirement);
146
- const symbol = extra.symbol || extra.name || 'tokens';
147
- const decimals = extra.decimals || 6;
148
- const amount = Number(rawAmount) / Math.pow(10, decimals);
161
+ const symbol = payment?.symbol || extra.symbol || extra.name || 'tokens';
162
+ let amount = payment?.usd;
163
+ if (typeof amount !== 'number') {
164
+ const decimals = extra.decimals || 6;
165
+ amount = Number(resolvePaymentAmount(requirement)) / Math.pow(10, decimals);
166
+ }
149
167
  const chain = requirement.network || requirement.chain || 'unknown';
150
168
  return `${amount} ${symbol} on ${chain}`;
151
169
  }
@@ -213,11 +231,11 @@ async function prepareRequirement(requirement) {
213
231
  * A rejected, timed-out, or malformed signature throws: the user was already
214
232
  * prompted, so the caller must not prompt again for another option.
215
233
  */
216
- async function signRequirement(requirement, fromAddress, typedData, resource) {
234
+ async function signRequirement(requirement, fromAddress, typedData, resource, payment) {
217
235
  const typedDataJson = JSON.stringify(typedData);
218
236
 
219
237
  // Log payment info to stderr (stdout is for JSON output)
220
- const amountStr = formatPaymentAmount(requirement);
238
+ const amountStr = formatPaymentAmount(requirement, payment);
221
239
  process.stderr.write(`x402: Requesting payment approval (${amountStr})...\n`);
222
240
 
223
241
  // Sign via walletconnect CLI (120s timeout for user approval)
@@ -302,7 +320,7 @@ export async function* createWalletConnectPaymentSignatures(paymentRequirements,
302
320
  continue;
303
321
  }
304
322
  // The charge comes before the approval prompt, so an over-cap option never prompts.
305
- const signed = await signWithSessionCharge(payment, () => signRequirement(requirement, fromAddress, typedData, resource));
323
+ const signed = await signWithSessionCharge(payment, () => signRequirement(requirement, fromAddress, typedData, resource, payment));
306
324
  if (!signed.ok) {
307
325
  console.error(`[x402] Skipping ${requirement.network} WalletConnect option: ${signed.reason}`);
308
326
  options.onCapRefusal?.(signed.reason);