nansen-cli 2.4.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.
@@ -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) 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}`);
@@ -933,11 +981,8 @@ EXAMPLES:
933
981
 
934
982
  let { pubkey, walletType, walletInfo } = resolved;
935
983
 
936
- // For local wallets, load private key for auth
937
- if (walletType === 'local') {
938
- const privateKeyHex = getLocalWalletPrivateKey(resolved.walletName);
939
- walletInfo = { privateKeyHex };
940
- }
984
+ // List is authenticated, so hydrate the selected signer before auth.
985
+ walletInfo = await hydrateSolanaWalletSigner(resolved);
941
986
 
942
987
  const token = await authenticate(pubkey, walletType, walletInfo, log);
943
988
 
@@ -972,6 +1017,7 @@ EXAMPLES:
972
1017
  rejectBlankOption(options.wallet, 'wallet', '<name>');
973
1018
  const orderId = options.order || options['order-id'] || args[0];
974
1019
  const walletName = options.wallet;
1020
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
975
1021
 
976
1022
  if (!orderId) {
977
1023
  log(`
@@ -980,6 +1026,8 @@ Usage: nansen trade limit-order cancel --order <orderId>
980
1026
  OPTIONS:
981
1027
  --order <id> Order ID to cancel
982
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
983
1031
 
984
1032
  EXAMPLES:
985
1033
  nansen trade limit-order cancel --order abc123`);
@@ -993,10 +1041,28 @@ EXAMPLES:
993
1041
 
994
1042
  let { pubkey, walletType, walletInfo } = resolved;
995
1043
 
996
- if (walletType === 'local') {
997
- const privateKeyHex = getLocalWalletPrivateKey(resolved.walletName);
998
- walletInfo = { privateKeyHex };
999
- }
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);
1000
1066
 
1001
1067
  log(`\nCancelling order ${orderId}...`);
1002
1068
 
@@ -1093,6 +1159,7 @@ EXAMPLES:
1093
1159
  log('');
1094
1160
 
1095
1161
  } catch (err) {
1162
+ if (err.reported) throw err;
1096
1163
  log(`Error: ${err.message}`);
1097
1164
  if (err.details) log(` Details: ${JSON.stringify(err.details)}`);
1098
1165
  exit(1);
@@ -1158,10 +1225,7 @@ EXAMPLES:
1158
1225
 
1159
1226
  let { pubkey, walletType, walletInfo } = resolved;
1160
1227
 
1161
- if (walletType === 'local') {
1162
- const privateKeyHex = getLocalWalletPrivateKey(resolved.walletName);
1163
- walletInfo = { privateKeyHex };
1164
- }
1228
+ walletInfo = await hydrateSolanaWalletSigner(resolved);
1165
1229
 
1166
1230
  log(`\nUpdating order ${orderId}...`);
1167
1231