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
@@ -10,7 +10,7 @@ import { rejectBlankOption } from './query-options.js';
10
10
  import fs from 'fs';
11
11
  import path from 'path';
12
12
  import { base58Encode, exportWallet, getWalletConfig, showWallet } from './wallet.js';
13
- import { signEd25519, base58Decode, parseAmount, getTokenInfo } from './transfer.js';
13
+ import { signEd25519, base58Decode, parseAmount, formatAmount as formatTokenUnits, getTokenInfo } from './transfer.js';
14
14
  import { signSolanaTransaction, resolveTokenAddress } from './trading.js';
15
15
  import {
16
16
  assertSolanaInstructionsSafe,
@@ -28,6 +28,7 @@ import { validateTokenAddress, telemetryHeaders, packageVersion } from './api.js
28
28
  import { getWalletConnectAddress, sendSolanaTransactionViaWalletConnect, signSolanaMessageViaWalletConnect } from './walletconnect-trading.js';
29
29
  import { retrievePassword } from './keychain.js';
30
30
  import { CHAIN_RPCS } from './rpc-urls.js';
31
+ import { formatPlan, guardExecution, resolveExecuteGuard } from './execute-guard.js';
31
32
 
32
33
  // ============= Constants =============
33
34
 
@@ -285,6 +286,9 @@ export async function authenticate(walletPubkey, walletType, walletInfo, log = (
285
286
  * Resolve a Solana wallet for limit orders.
286
287
  * Follows the same 3-way dispatch as trading.js: WalletConnect / named / default.
287
288
  *
289
+ * This phase resolves public identity only. Signer secrets/clients are hydrated
290
+ * separately after acknowledgement so previews and declines cannot require them.
291
+ *
288
292
  * @returns {{ pubkey, walletType, walletInfo, privyWalletIds }}
289
293
  */
290
294
  export async function resolveSolanaWallet(walletName, deps = {}) {
@@ -323,12 +327,10 @@ export async function resolveSolanaWallet(walletName, deps = {}) {
323
327
  }
324
328
 
325
329
  if (wallet.provider === 'privy') {
326
- const { PrivyClient } = await import('./privy.js');
327
- const privyClient = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
328
330
  return {
329
331
  pubkey: wallet.solana,
330
332
  walletType: 'privy',
331
- walletInfo: { privyClient, walletId: wallet.privyWalletIds?.solana },
333
+ walletInfo: {},
332
334
  privyWalletIds: wallet.privyWalletIds,
333
335
  };
334
336
  }
@@ -343,6 +345,24 @@ export async function resolveSolanaWallet(walletName, deps = {}) {
343
345
  };
344
346
  }
345
347
 
348
+ /** Hydrate the signer only once a guarded operation is allowed to proceed. */
349
+ async function hydrateSolanaWalletSigner(resolved) {
350
+ if (resolved.walletType === 'local') {
351
+ return { privateKeyHex: getLocalWalletPrivateKey(resolved.walletName) };
352
+ }
353
+ if (resolved.walletType === 'privy') {
354
+ const { PrivyClient, assertPrivyWalletAddress } = await import('./privy.js');
355
+ const privyClient = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
356
+ const walletId = resolved.privyWalletIds?.solana;
357
+ // Bind the Privy wallet ID to the locally stored address before anything
358
+ // is signed. Runs here rather than at resolution so --dry-run and a
359
+ // declined prompt stay offline.
360
+ await assertPrivyWalletAddress(privyClient, walletId, resolved.pubkey, 'solana');
361
+ return { privyClient, walletId };
362
+ }
363
+ return resolved.walletInfo;
364
+ }
365
+
346
366
  /**
347
367
  * Get the private key hex for a local wallet, prompting for password if needed.
348
368
  */
@@ -621,7 +641,14 @@ function formatOrder(order, index) {
621
641
  * Build limit order command handlers for CLI integration.
622
642
  */
623
643
  export function buildLimitOrderCommands(deps = {}) {
624
- const { log = console.log, exit = process.exit } = deps;
644
+ const {
645
+ log = console.log,
646
+ exit = process.exit,
647
+ promptFn,
648
+ confirmationLog = log,
649
+ isTTY = false,
650
+ env = process.env,
651
+ } = deps;
625
652
 
626
653
  return {
627
654
  'create': async (args, apiInstance, flags, options) => {
@@ -638,6 +665,7 @@ export function buildLimitOrderCommands(deps = {}) {
638
665
  const slippageBpsRaw = options['slippage-bps'];
639
666
  const expiresStr = options.expires || '30d';
640
667
  const walletName = options.wallet;
668
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
641
669
 
642
670
  if (!from || !to || !amount || triggerPrice == null || !triggerMintRaw || !triggerCondition) {
643
671
  log(`
@@ -653,6 +681,8 @@ OPTIONS:
653
681
  --slippage-bps <bps> Whole integer bps, 0-10000 (100 = 1%), omit for auto
654
682
  --expires <duration> Expiry duration: "24h", "7d", "30d" (default: 30d)
655
683
  --wallet <name> Wallet name (or "walletconnect"/"wc")
684
+ --dry-run Preview the validated intent without API calls or signing
685
+ --yes, -y Skip the interactive confirmation prompt
656
686
 
657
687
  EXAMPLES:
658
688
  # Sell 1 SOL for USDC when SOL drops below $80
@@ -693,49 +723,43 @@ EXAMPLES:
693
723
  return;
694
724
  }
695
725
 
696
- // Amount is always in human-readable token units (e.g. 1.5 = 1.5 SOL)
697
- // Converted to base units (lamports) internally
726
+ // Validate the human amount locally before showing an intent preview. Known
727
+ // tokens are converted exactly without I/O. A custom token needs a
728
+ // read-only decimals lookup: a real run does it before the prompt, so the
729
+ // user never approves an amount that then fails to convert; --dry-run
730
+ // skips it to stay offline and says so in the plan.
731
+ const amountString = String(amount).trim();
732
+ if (!/^\d+(\.\d+)?$/.test(amountString) || /^0+(\.0+)?$/.test(amountString)) {
733
+ log('Error: --amount must be a positive number in token units (e.g. 1.5 for 1.5 SOL, 80 for 80 USDC).');
734
+ exit(1);
735
+ return;
736
+ }
698
737
  let amountBaseUnits;
699
- try {
700
- const num = Number(amount);
701
- if (isNaN(num) || num <= 0) {
702
- log('Error: --amount must be a positive number in token units (e.g. 1.5 for 1.5 SOL, 80 for 80 USDC).');
738
+ const knownFromInfo = KNOWN_SOLANA_TOKENS[from];
739
+ let fromDecimals = knownFromInfo?.decimals;
740
+ if (fromDecimals === undefined && !guard.dryRun) {
741
+ try {
742
+ fromDecimals = (await getTokenInfo(CHAIN_RPCS.solana, from)).decimals;
743
+ } catch (err) {
744
+ log(`Error: Could not resolve decimals for ${from}: ${err.message}`);
703
745
  exit(1);
704
746
  return;
705
747
  }
706
- const fromInfo = KNOWN_SOLANA_TOKENS[from];
707
- let decimals;
708
- if (fromInfo) {
709
- decimals = fromInfo.decimals;
710
- } else {
711
- const tokenInfo = await getTokenInfo(CHAIN_RPCS.solana, from);
712
- decimals = tokenInfo.decimals;
713
- }
748
+ }
749
+ if (fromDecimals !== undefined) {
714
750
  try {
715
- amountBaseUnits = String(parseAmount(String(amount), decimals));
716
- } catch (err) {
717
751
  // parseAmount rejects an amount that truncates to zero base units at
718
752
  // this token's precision — a decimals problem only in name.
753
+ amountBaseUnits = String(parseAmount(amountString, fromDecimals));
754
+ } catch (err) {
719
755
  log(`Error: ${err.message}`);
720
756
  exit(1);
721
757
  return;
722
758
  }
723
- } catch (err) {
724
- log(`Error: Could not resolve decimals for ${from}: ${err.message}`);
725
- exit(1);
726
- return;
727
759
  }
728
760
 
729
- // Fail fast on a native-SOL amount too small for outcome verification to bound by
730
- // magnitude (see assertLimitOrderDepositOutcome's NATIVE_FEE_RENT_SLACK_LAMPORTS
731
- // floor) — otherwise this would only surface as a LIMIT_ORDER_OUTCOME_MISMATCH
732
- // after crafting and simulating the deposit transaction, well into the flow.
733
- // Gated on hasSolanaSimulationRpc deliberately: the floor is a pre-empt of the
734
- // magnitude check, so it only applies when that check would actually run. In a
735
- // degraded (no-sim-RPC) environment there is no magnitude bound to pre-empt — the
736
- // deposit falls back to the static gate alone (verifyLimitOrderOutcome already warns
737
- // that outcome verification is unavailable), so blocking a small amount here would
738
- // add a floor that the rest of that path doesn't enforce.
761
+ // This bound is local once SOL's fixed decimals are known, so retain the
762
+ // existing fail-fast behavior before wallet resolution or acknowledgement.
739
763
  if (from === WSOL_MINT && hasSolanaSimulationRpc('solana') && BigInt(amountBaseUnits) <= NATIVE_FEE_RENT_SLACK_LAMPORTS) {
740
764
  log(`Error: SOL deposit amount (${amountBaseUnits} lamports) is too small to verify against network fee/rent noise (${NATIVE_FEE_RENT_SLACK_LAMPORTS} lamports). Use a larger amount.`);
741
765
  exit(1);
@@ -776,11 +800,36 @@ EXAMPLES:
776
800
 
777
801
  let { pubkey, walletType, walletInfo } = resolved;
778
802
 
779
- // For local wallets, load private key now
780
- if (walletType === 'local') {
781
- const privateKeyHex = getLocalWalletPrivateKey(resolved.walletName);
782
- walletInfo = { privateKeyHex };
783
- }
803
+ const createPlan = formatPlan('Create limit order plan', [
804
+ ['Wallet', pubkey],
805
+ // Show what will be signed: parseAmount truncates digits beyond the
806
+ // token's decimals, so the raw --amount text can differ from it.
807
+ ['Sell', amountBaseUnits === undefined
808
+ ? `${amountString} ${tokenLabel(from)} (token decimals not checked in --dry-run)`
809
+ : knownFromInfo
810
+ ? `${formatAmount(amountBaseUnits, from)} ${from}`
811
+ : `${formatTokenUnits(BigInt(amountBaseUnits), fromDecimals)} ${from} (${amountBaseUnits} base units)`],
812
+ ['Buy', tokenLabel(to)],
813
+ ['Trigger', `${tokenLabel(triggerMint)} ${triggerCondition} $${price}`],
814
+ ['Slippage', slippageBps != null ? `${slippageBps} bps` : 'auto'],
815
+ ['Expires', expiresAt == null ? 'never' : `${expiresStr} (${new Date(expiresAt).toISOString()})`],
816
+ ], ['Transaction validation and order submission run only after confirmation.']);
817
+ const proceed = await guardExecution({
818
+ plan: createPlan,
819
+ ...guard,
820
+ promptFn,
821
+ log,
822
+ confirmationLog,
823
+ question: 'Create this limit order? [y/N] ',
824
+ dryRunNotice: [
825
+ '\n DRY RUN — no transaction was signed and no order was submitted.',
826
+ ' Re-run without --dry-run to validate, sign, and submit this limit order.\n',
827
+ ],
828
+ });
829
+ if (!proceed) return;
830
+
831
+ // Hydrate local/Privy signing material only after dry-run/prompt.
832
+ walletInfo = await hydrateSolanaWalletSigner(resolved);
784
833
 
785
834
  log(`\nCreating limit order on Solana...`);
786
835
  log(` Wallet: ${pubkey}`);
@@ -888,6 +937,7 @@ EXAMPLES:
888
937
  log('');
889
938
 
890
939
  } catch (err) {
940
+ if (err.reported) throw err;
891
941
  log(`Error: ${err.message}`);
892
942
  if (err.details) log(` Details: ${JSON.stringify(err.details)}`);
893
943
  if (err.cause) log(` Cause: ${err.cause.message || err.cause}`);
@@ -905,10 +955,17 @@ EXAMPLES:
905
955
  const state = options.state;
906
956
  const mint = options.mint ? resolveTokenAddress(options.mint, 'solana') : undefined;
907
957
  const limit = options.limit || 20;
908
- const offset = options.offset || 0;
958
+ // parseArgs keeps numbers as strings; the footer below adds to offset.
959
+ const offset = options.offset == null ? 0 : Number(options.offset);
909
960
  const sort = options.sort;
910
961
  const dir = options.dir || 'desc';
911
962
 
963
+ if (!/^\d+$/.test(String(options.offset ?? 0)) || !Number.isSafeInteger(offset)) {
964
+ log(`Error: --offset must be a non-negative integer; received: ${options.offset}`);
965
+ exit(1);
966
+ return;
967
+ }
968
+
912
969
  if (mint) {
913
970
  const mintValidation = validateTokenAddress(mint, 'solana');
914
971
  if (!mintValidation.valid) {
@@ -924,11 +981,8 @@ EXAMPLES:
924
981
 
925
982
  let { pubkey, walletType, walletInfo } = resolved;
926
983
 
927
- // For local wallets, load private key for auth
928
- if (walletType === 'local') {
929
- const privateKeyHex = getLocalWalletPrivateKey(resolved.walletName);
930
- walletInfo = { privateKeyHex };
931
- }
984
+ // List is authenticated, so hydrate the selected signer before auth.
985
+ walletInfo = await hydrateSolanaWalletSigner(resolved);
932
986
 
933
987
  const token = await authenticate(pubkey, walletType, walletInfo, log);
934
988
 
@@ -963,6 +1017,7 @@ EXAMPLES:
963
1017
  rejectBlankOption(options.wallet, 'wallet', '<name>');
964
1018
  const orderId = options.order || options['order-id'] || args[0];
965
1019
  const walletName = options.wallet;
1020
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
966
1021
 
967
1022
  if (!orderId) {
968
1023
  log(`
@@ -971,6 +1026,8 @@ Usage: nansen trade limit-order cancel --order <orderId>
971
1026
  OPTIONS:
972
1027
  --order <id> Order ID to cancel
973
1028
  --wallet <name> Wallet name (or "walletconnect"/"wc")
1029
+ --dry-run Preview without requesting a cancellation transaction
1030
+ --yes, -y Skip the interactive confirmation prompt
974
1031
 
975
1032
  EXAMPLES:
976
1033
  nansen trade limit-order cancel --order abc123`);
@@ -984,10 +1041,28 @@ EXAMPLES:
984
1041
 
985
1042
  let { pubkey, walletType, walletInfo } = resolved;
986
1043
 
987
- if (walletType === 'local') {
988
- const privateKeyHex = getLocalWalletPrivateKey(resolved.walletName);
989
- walletInfo = { privateKeyHex };
990
- }
1044
+ const cancelPlan = formatPlan('Cancel limit order plan', [
1045
+ ['Order', orderId],
1046
+ ['Wallet', pubkey],
1047
+ ], [
1048
+ 'The active order and expected refund are verified after confirmation.',
1049
+ 'No cancellation transaction is requested while previewing this intent.',
1050
+ ]);
1051
+ const proceed = await guardExecution({
1052
+ plan: cancelPlan,
1053
+ ...guard,
1054
+ promptFn,
1055
+ log,
1056
+ confirmationLog,
1057
+ question: 'Cancel this limit order? [y/N] ',
1058
+ dryRunNotice: [
1059
+ '\n DRY RUN — no transaction was signed and no cancellation request was created or consumed.',
1060
+ ' Re-run without --dry-run to verify and cancel this limit order.\n',
1061
+ ],
1062
+ });
1063
+ if (!proceed) return;
1064
+
1065
+ walletInfo = await hydrateSolanaWalletSigner(resolved);
991
1066
 
992
1067
  log(`\nCancelling order ${orderId}...`);
993
1068
 
@@ -1084,6 +1159,7 @@ EXAMPLES:
1084
1159
  log('');
1085
1160
 
1086
1161
  } catch (err) {
1162
+ if (err.reported) throw err;
1087
1163
  log(`Error: ${err.message}`);
1088
1164
  if (err.details) log(` Details: ${JSON.stringify(err.details)}`);
1089
1165
  exit(1);
@@ -1149,10 +1225,7 @@ EXAMPLES:
1149
1225
 
1150
1226
  let { pubkey, walletType, walletInfo } = resolved;
1151
1227
 
1152
- if (walletType === 'local') {
1153
- const privateKeyHex = getLocalWalletPrivateKey(resolved.walletName);
1154
- walletInfo = { privateKeyHex };
1155
- }
1228
+ walletInfo = await hydrateSolanaWalletSigner(resolved);
1156
1229
 
1157
1230
  log(`\nUpdating order ${orderId}...`);
1158
1231