nansen-cli 2.4.0 → 2.6.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.
@@ -126,9 +126,13 @@ const CATEGORY_ALIASES = { tgm: 'token', sm: 'smart-money', prof: 'profiler', po
126
126
  // Categories that still run without the `research` prefix.
127
127
  const TOP_LEVEL_CATEGORIES = new Set(['smart-money', 'profiler', 'token', 'search', 'portfolio', 'prediction-market']);
128
128
  // Subcommand spellings a handler accepts besides the schema name.
129
- const SUBCOMMAND_ALIASES = { portfolio: { 'defi-holdings': 'defi' } };
130
- // Categories whose handler does its own routing and never calls the API.
131
- const UNVALIDATED_CATEGORIES = new Set(['points']);
129
+ export const SUBCOMMAND_ALIASES = { portfolio: { 'defi-holdings': 'defi' } };
130
+ // Commands whose endpoint was removed. Their handler still answers with
131
+ // COMMAND_UNAVAILABLE, both as `nansen <name>` and `nansen research <name>`,
132
+ // but they are left out of the schema, help listings, completions and "did
133
+ // you mean" suggestions so agents do not spend a call on them. Validation
134
+ // skips them, since the schema no longer has an entry to check against.
135
+ export const UNAVAILABLE_COMMANDS = new Set(['points']);
132
136
 
133
137
  /**
134
138
  * The research schema entry a command line runs, or null when the command is
@@ -147,6 +151,7 @@ export function resolveResearchCommand(schema, command, subArgs) {
147
151
  const raw = subArgs[0];
148
152
  if (!raw || raw === 'help') return null;
149
153
  category = Object.hasOwn(CATEGORY_ALIASES, raw) ? CATEGORY_ALIASES[raw] : raw;
154
+ if (UNAVAILABLE_COMMANDS.has(category)) return null;
150
155
  if (!Object.hasOwn(research, category)) {
151
156
  throw unknownCommandError('research category', raw, Object.keys(research));
152
157
  }
@@ -163,7 +168,6 @@ export function resolveResearchCommand(schema, command, subArgs) {
163
168
  } else {
164
169
  return null;
165
170
  }
166
- if (UNVALIDATED_CATEGORIES.has(category)) return null;
167
171
 
168
172
  const entry = research[category];
169
173
  if (!entry.subcommands) {
@@ -377,8 +381,8 @@ function valueErrors(name, spec, value) {
377
381
 
378
382
  /**
379
383
  * Check a research command's options before it runs. Throws one NansenError
380
- * listing every problem (see validationError). On success it rewrites
381
- * --chain/--chains in `options` to their canonical spelling (lowercase, REST
384
+ * listing every problem (see validationError). On success it renames aliases
385
+ * to their schema name, and rewrites --chain/--chains in `options` to their canonical spelling (lowercase, REST
382
386
  * aliases such as bsc -> bnb applied), as the API itself would, and turns
383
387
  * --chains into an array.
384
388
  */
@@ -395,9 +399,18 @@ export function validateResearchInput(resolved, { flags = {}, options = {}, endp
395
399
  ...Object.entries(options).map(([name, value]) => [name, value]),
396
400
  ...Object.entries(flags).filter(([name, value]) => value && !(name in options)).map(([name, value]) => [name, value]),
397
401
  ];
402
+ const spelled = new Map(); // schema name -> the spelling that was given
398
403
  for (const [raw, value] of supplied) {
399
404
  const canonical = names.get(raw);
400
405
  if (canonical) {
406
+ // `--token A --token-address B` names one input twice; the handler
407
+ // would silently use one of them.
408
+ if (spelled.has(canonical)) {
409
+ errors.push(fieldError(`--${canonical}`, 'invalid_field_value',
410
+ `Options '--${spelled.get(canonical)}' and '--${raw}' are the same input (--${canonical}); pass one.`));
411
+ continue;
412
+ }
413
+ spelled.set(canonical, raw);
401
414
  given.set(canonical, value);
402
415
  continue;
403
416
  }
@@ -411,8 +424,12 @@ export function validateResearchInput(resolved, { flags = {}, options = {}, endp
411
424
  continue;
412
425
  }
413
426
  const field = raw.length === 1 ? `-${raw}` : `--${raw}`;
427
+ // --days is the lookback flag elsewhere; here the window is text (24h, 7d).
428
+ const hint = raw === 'days' && leaf.options?.timeframe && !names.has('days')
429
+ ? ' Use --timeframe instead (for example --timeframe 7d); this command takes a time window, not a number of days.'
430
+ : '';
414
431
  errors.push(fieldError(field, 'unknown_field',
415
- `Option '${field}' is not recognized by ${path}. Command-specific options: ${visible.join(', ') || 'none'}. Common options also apply; see: nansen schema.`));
432
+ `Option '${field}' is not recognized by ${path}.${hint} Command-specific options: ${visible.join(', ') || 'none'}. Common options also apply; see: nansen schema.`));
416
433
  }
417
434
 
418
435
  for (const [name, value] of given) {
@@ -443,9 +460,25 @@ export function validateResearchInput(resolved, { flags = {}, options = {}, endp
443
460
  }
444
461
 
445
462
  if (errors.length) throw validationError(errors);
463
+ canonicalizeOptionNames(options, flags, names);
446
464
  normalizeChainOptions(options, names);
447
465
  }
448
466
 
467
+ /**
468
+ * Move every alias to its schema name (--token-address -> --token), so a
469
+ * handler reads one name per input and an alias needs only a schema entry.
470
+ */
471
+ function canonicalizeOptionNames(options, flags, names) {
472
+ for (const [raw, canonical] of names) {
473
+ if (raw === canonical) continue;
474
+ for (const bag of [options, flags]) {
475
+ if (!Object.hasOwn(bag, raw)) continue;
476
+ bag[canonical] = bag[raw];
477
+ delete bag[raw];
478
+ }
479
+ }
480
+ }
481
+
449
482
  /** Reject an output format the CLI cannot write. */
450
483
  export function validateOutputOptions({ flags = {}, options = {} } = {}) {
451
484
  // --fields is applied after the response arrives; check its shape here so
@@ -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,14 +327,10 @@ export async function resolveSolanaWallet(walletName, deps = {}) {
323
327
  }
324
328
 
325
329
  if (wallet.provider === 'privy') {
326
- const { PrivyClient, assertPrivyWalletAddress } = await import('./privy.js');
327
- const privyClient = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
328
- const walletId = wallet.privyWalletIds?.solana;
329
- await assertPrivyWalletAddress(privyClient, walletId, wallet.solana, 'solana');
330
330
  return {
331
331
  pubkey: wallet.solana,
332
332
  walletType: 'privy',
333
- walletInfo: { privyClient, walletId },
333
+ walletInfo: {},
334
334
  privyWalletIds: wallet.privyWalletIds,
335
335
  };
336
336
  }
@@ -345,6 +345,24 @@ export async function resolveSolanaWallet(walletName, deps = {}) {
345
345
  };
346
346
  }
347
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
+
348
366
  /**
349
367
  * Get the private key hex for a local wallet, prompting for password if needed.
350
368
  */
@@ -623,7 +641,14 @@ function formatOrder(order, index) {
623
641
  * Build limit order command handlers for CLI integration.
624
642
  */
625
643
  export function buildLimitOrderCommands(deps = {}) {
626
- 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;
627
652
 
628
653
  return {
629
654
  'create': async (args, apiInstance, flags, options) => {
@@ -640,6 +665,7 @@ export function buildLimitOrderCommands(deps = {}) {
640
665
  const slippageBpsRaw = options['slippage-bps'];
641
666
  const expiresStr = options.expires || '30d';
642
667
  const walletName = options.wallet;
668
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
643
669
 
644
670
  if (!from || !to || !amount || triggerPrice == null || !triggerMintRaw || !triggerCondition) {
645
671
  log(`
@@ -655,6 +681,8 @@ OPTIONS:
655
681
  --slippage-bps <bps> Whole integer bps, 0-10000 (100 = 1%), omit for auto
656
682
  --expires <duration> Expiry duration: "24h", "7d", "30d" (default: 30d)
657
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
658
686
 
659
687
  EXAMPLES:
660
688
  # Sell 1 SOL for USDC when SOL drops below $80
@@ -695,49 +723,43 @@ EXAMPLES:
695
723
  return;
696
724
  }
697
725
 
698
- // Amount is always in human-readable token units (e.g. 1.5 = 1.5 SOL)
699
- // 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
+ }
700
737
  let amountBaseUnits;
701
- try {
702
- const num = Number(amount);
703
- if (isNaN(num) || num <= 0) {
704
- 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}`);
705
745
  exit(1);
706
746
  return;
707
747
  }
708
- const fromInfo = KNOWN_SOLANA_TOKENS[from];
709
- let decimals;
710
- if (fromInfo) {
711
- decimals = fromInfo.decimals;
712
- } else {
713
- const tokenInfo = await getTokenInfo(CHAIN_RPCS.solana, from);
714
- decimals = tokenInfo.decimals;
715
- }
748
+ }
749
+ if (fromDecimals !== undefined) {
716
750
  try {
717
- amountBaseUnits = String(parseAmount(String(amount), decimals));
718
- } catch (err) {
719
751
  // parseAmount rejects an amount that truncates to zero base units at
720
752
  // this token's precision — a decimals problem only in name.
753
+ amountBaseUnits = String(parseAmount(amountString, fromDecimals));
754
+ } catch (err) {
721
755
  log(`Error: ${err.message}`);
722
756
  exit(1);
723
757
  return;
724
758
  }
725
- } catch (err) {
726
- log(`Error: Could not resolve decimals for ${from}: ${err.message}`);
727
- exit(1);
728
- return;
729
759
  }
730
760
 
731
- // Fail fast on a native-SOL amount too small for outcome verification to bound by
732
- // magnitude (see assertLimitOrderDepositOutcome's NATIVE_FEE_RENT_SLACK_LAMPORTS
733
- // floor) — otherwise this would only surface as a LIMIT_ORDER_OUTCOME_MISMATCH
734
- // after crafting and simulating the deposit transaction, well into the flow.
735
- // Gated on hasSolanaSimulationRpc deliberately: the floor is a pre-empt of the
736
- // magnitude check, so it only applies when that check would actually run. In a
737
- // degraded (no-sim-RPC) environment there is no magnitude bound to pre-empt — the
738
- // deposit falls back to the static gate alone (verifyLimitOrderOutcome already warns
739
- // that outcome verification is unavailable), so blocking a small amount here would
740
- // 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.
741
763
  if (from === WSOL_MINT && hasSolanaSimulationRpc('solana') && BigInt(amountBaseUnits) <= NATIVE_FEE_RENT_SLACK_LAMPORTS) {
742
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.`);
743
765
  exit(1);
@@ -778,11 +800,36 @@ EXAMPLES:
778
800
 
779
801
  let { pubkey, walletType, walletInfo } = resolved;
780
802
 
781
- // For local wallets, load private key now
782
- if (walletType === 'local') {
783
- const privateKeyHex = getLocalWalletPrivateKey(resolved.walletName);
784
- walletInfo = { privateKeyHex };
785
- }
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);
786
833
 
787
834
  log(`\nCreating limit order on Solana...`);
788
835
  log(` Wallet: ${pubkey}`);
@@ -890,6 +937,7 @@ EXAMPLES:
890
937
  log('');
891
938
 
892
939
  } catch (err) {
940
+ if (err.reported || err.code === 'CONFIRMATION_REQUIRED') throw err;
893
941
  log(`Error: ${err.message}`);
894
942
  if (err.details) log(` Details: ${JSON.stringify(err.details)}`);
895
943
  if (err.cause) log(` Cause: ${err.cause.message || err.cause}`);
@@ -898,6 +946,7 @@ EXAMPLES:
898
946
  },
899
947
 
900
948
  'list': async (args, apiInstance, flags, options) => {
949
+ rejectBlankOption(options.token, 'token', 'SOL');
901
950
  rejectBlankOption(options.mint, 'mint', 'SOL');
902
951
  rejectBlankOption(options.limit, 'limit', '20');
903
952
  rejectBlankOption(options.offset, 'offset', '0');
@@ -905,7 +954,14 @@ EXAMPLES:
905
954
  rejectBlankOption(options.wallet, 'wallet', '<name>');
906
955
  const walletName = options.wallet;
907
956
  const state = options.state;
908
- const mint = options.mint ? resolveTokenAddress(options.mint, 'solana') : undefined;
957
+ // --mint is the old name of --token.
958
+ if (options.token !== undefined && options.mint !== undefined) {
959
+ log(`Error: --token ${options.token} and --mint ${options.mint} are the same input; pass one.`);
960
+ exit(1);
961
+ return;
962
+ }
963
+ const tokenArg = options.token ?? options.mint;
964
+ const mint = tokenArg ? resolveTokenAddress(tokenArg, 'solana') : undefined;
909
965
  const limit = options.limit || 20;
910
966
  // parseArgs keeps numbers as strings; the footer below adds to offset.
911
967
  const offset = options.offset == null ? 0 : Number(options.offset);
@@ -921,7 +977,7 @@ EXAMPLES:
921
977
  if (mint) {
922
978
  const mintValidation = validateTokenAddress(mint, 'solana');
923
979
  if (!mintValidation.valid) {
924
- log(`Error: Invalid --mint address: ${mintValidation.error}`);
980
+ log(`Error: Invalid --token address: ${mintValidation.error}`);
925
981
  exit(1);
926
982
  return;
927
983
  }
@@ -933,11 +989,8 @@ EXAMPLES:
933
989
 
934
990
  let { pubkey, walletType, walletInfo } = resolved;
935
991
 
936
- // For local wallets, load private key for auth
937
- if (walletType === 'local') {
938
- const privateKeyHex = getLocalWalletPrivateKey(resolved.walletName);
939
- walletInfo = { privateKeyHex };
940
- }
992
+ // List is authenticated, so hydrate the selected signer before auth.
993
+ walletInfo = await hydrateSolanaWalletSigner(resolved);
941
994
 
942
995
  const token = await authenticate(pubkey, walletType, walletInfo, log);
943
996
 
@@ -972,6 +1025,7 @@ EXAMPLES:
972
1025
  rejectBlankOption(options.wallet, 'wallet', '<name>');
973
1026
  const orderId = options.order || options['order-id'] || args[0];
974
1027
  const walletName = options.wallet;
1028
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
975
1029
 
976
1030
  if (!orderId) {
977
1031
  log(`
@@ -980,6 +1034,8 @@ Usage: nansen trade limit-order cancel --order <orderId>
980
1034
  OPTIONS:
981
1035
  --order <id> Order ID to cancel
982
1036
  --wallet <name> Wallet name (or "walletconnect"/"wc")
1037
+ --dry-run Preview without requesting a cancellation transaction
1038
+ --yes, -y Skip the interactive confirmation prompt
983
1039
 
984
1040
  EXAMPLES:
985
1041
  nansen trade limit-order cancel --order abc123`);
@@ -993,10 +1049,28 @@ EXAMPLES:
993
1049
 
994
1050
  let { pubkey, walletType, walletInfo } = resolved;
995
1051
 
996
- if (walletType === 'local') {
997
- const privateKeyHex = getLocalWalletPrivateKey(resolved.walletName);
998
- walletInfo = { privateKeyHex };
999
- }
1052
+ const cancelPlan = formatPlan('Cancel limit order plan', [
1053
+ ['Order', orderId],
1054
+ ['Wallet', pubkey],
1055
+ ], [
1056
+ 'The active order and expected refund are verified after confirmation.',
1057
+ 'No cancellation transaction is requested while previewing this intent.',
1058
+ ]);
1059
+ const proceed = await guardExecution({
1060
+ plan: cancelPlan,
1061
+ ...guard,
1062
+ promptFn,
1063
+ log,
1064
+ confirmationLog,
1065
+ question: 'Cancel this limit order? [y/N] ',
1066
+ dryRunNotice: [
1067
+ '\n DRY RUN — no transaction was signed and no cancellation request was created or consumed.',
1068
+ ' Re-run without --dry-run to verify and cancel this limit order.\n',
1069
+ ],
1070
+ });
1071
+ if (!proceed) return;
1072
+
1073
+ walletInfo = await hydrateSolanaWalletSigner(resolved);
1000
1074
 
1001
1075
  log(`\nCancelling order ${orderId}...`);
1002
1076
 
@@ -1093,6 +1167,7 @@ EXAMPLES:
1093
1167
  log('');
1094
1168
 
1095
1169
  } catch (err) {
1170
+ if (err.reported || err.code === 'CONFIRMATION_REQUIRED') throw err;
1096
1171
  log(`Error: ${err.message}`);
1097
1172
  if (err.details) log(` Details: ${JSON.stringify(err.details)}`);
1098
1173
  exit(1);
@@ -1158,10 +1233,7 @@ EXAMPLES:
1158
1233
 
1159
1234
  let { pubkey, walletType, walletInfo } = resolved;
1160
1235
 
1161
- if (walletType === 'local') {
1162
- const privateKeyHex = getLocalWalletPrivateKey(resolved.walletName);
1163
- walletInfo = { privateKeyHex };
1164
- }
1236
+ walletInfo = await hydrateSolanaWalletSigner(resolved);
1165
1237
 
1166
1238
  log(`\nUpdating order ${orderId}...`);
1167
1239