nansen-cli 2.3.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 (71) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +32 -32
  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 +17 -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 +202 -97
  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 +188 -89
  50. package/src/commands/agent.js +2 -3
  51. package/src/commands/alerts.js +277 -9
  52. package/src/commands/feedback.js +98 -37
  53. package/src/commands/mcp.js +1 -1
  54. package/src/commands/research.js +14 -37
  55. package/src/cost-cache.js +33 -7
  56. package/src/doctor.js +14 -5
  57. package/src/error-codes.js +226 -0
  58. package/src/input-validation.js +551 -0
  59. package/src/limit-order.js +12 -3
  60. package/src/perp.js +2 -1
  61. package/src/privy.js +89 -11
  62. package/src/query-options.js +30 -7
  63. package/src/rpc-urls.js +3 -1
  64. package/src/schema.json +1137 -145
  65. package/src/solana-tx.js +4 -0
  66. package/src/trade-validation.js +167 -8
  67. package/src/trading.js +172 -12
  68. package/src/transfer.js +7 -1
  69. package/src/update-check.js +32 -5
  70. package/src/wallet.js +211 -57
  71. package/src/walletconnect-x402.js +14 -8
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';
@@ -139,13 +139,19 @@ export function buildPaymentSignatureHeader({ signature, authorization, resource
139
139
 
140
140
  /**
141
141
  * Format amount for human-readable display (e.g., "0.01 USDC")
142
+ *
143
+ * Prefers the policy decision, which scaled the amount with the known token's
144
+ * decimals; the server's `extra` rarely carries decimals, and the BSC tokens
145
+ * use 18, not 6.
142
146
  */
143
- function formatPaymentAmount(requirement) {
147
+ function formatPaymentAmount(requirement, payment) {
144
148
  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);
149
+ const symbol = payment?.symbol || extra.symbol || extra.name || 'tokens';
150
+ let amount = payment?.usd;
151
+ if (typeof amount !== 'number') {
152
+ const decimals = extra.decimals || 6;
153
+ amount = Number(resolvePaymentAmount(requirement)) / Math.pow(10, decimals);
154
+ }
149
155
  const chain = requirement.network || requirement.chain || 'unknown';
150
156
  return `${amount} ${symbol} on ${chain}`;
151
157
  }
@@ -213,11 +219,11 @@ async function prepareRequirement(requirement) {
213
219
  * A rejected, timed-out, or malformed signature throws: the user was already
214
220
  * prompted, so the caller must not prompt again for another option.
215
221
  */
216
- async function signRequirement(requirement, fromAddress, typedData, resource) {
222
+ async function signRequirement(requirement, fromAddress, typedData, resource, payment) {
217
223
  const typedDataJson = JSON.stringify(typedData);
218
224
 
219
225
  // Log payment info to stderr (stdout is for JSON output)
220
- const amountStr = formatPaymentAmount(requirement);
226
+ const amountStr = formatPaymentAmount(requirement, payment);
221
227
  process.stderr.write(`x402: Requesting payment approval (${amountStr})...\n`);
222
228
 
223
229
  // Sign via walletconnect CLI (120s timeout for user approval)
@@ -302,7 +308,7 @@ export async function* createWalletConnectPaymentSignatures(paymentRequirements,
302
308
  continue;
303
309
  }
304
310
  // 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));
311
+ const signed = await signWithSessionCharge(payment, () => signRequirement(requirement, fromAddress, typedData, resource, payment));
306
312
  if (!signed.ok) {
307
313
  console.error(`[x402] Skipping ${requirement.network} WalletConnect option: ${signed.reason}`);
308
314
  options.onCapRefusal?.(signed.reason);