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/perp.js CHANGED
@@ -11,6 +11,7 @@
11
11
 
12
12
  import { CommandError } from './api.js';
13
13
  import { signSecp256k1 } from './crypto.js';
14
+ import { formatPlan, guardExecution, resolveExecuteGuard } from './execute-guard.js';
14
15
  import {
15
16
  buildApproveBuilderFeeAction,
16
17
  buildCancelAction,
@@ -621,9 +622,10 @@ async function resolveSigningCtx(wallet, log) {
621
622
  log,
622
623
  };
623
624
  if (wallet.provider === 'privy') {
624
- const { PrivyClient } = await import('./privy.js');
625
+ const { PrivyClient, assertPrivyWalletAddress } = await import('./privy.js');
625
626
  ctx.privyClient = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
626
627
  ctx.privyWalletId = wallet.privyWalletIds?.evm;
628
+ await assertPrivyWalletAddress(ctx.privyClient, ctx.privyWalletId, wallet.address, 'evm');
627
629
  } else {
628
630
  ctx.privateKeyHex = resolvePrivateKey(wallet);
629
631
  }
@@ -657,14 +659,215 @@ function resolveCoin(options) {
657
659
  return String(raw ?? '').toUpperCase();
658
660
  }
659
661
 
662
+ // ── Preview + confirmation (--dry-run / --yes) ───────────────────────
663
+ //
664
+ // order/close/cancel/leverage share the acknowledgement gate of trade and
665
+ // bridge execute (src/execute-guard.js): --dry-run prints the plan and stops
666
+ // before anything is signed; an interactive terminal is asked to confirm;
667
+ // --yes / -y / NANSEN_YES=1 skips the question. Off a terminal the command
668
+ // proceeds unprompted, exactly as before.
669
+
670
+ const PERP_DRY_RUN_NOTICE = [
671
+ '\n DRY RUN — nothing was sent to Hyperliquid. No action was signed.',
672
+ ' Re-run without --dry-run to sign and submit it.\n',
673
+ ];
674
+
675
+ // A decimal string (a wire value, or a number's shortest form such as "1e-7")
676
+ // as an exact BigInt scaled by 10^scale. null when it isn't one.
677
+ function parseDecimal(value) {
678
+ const match = /^([-+]?)(\d*)(?:\.(\d*))?(?:e([-+]?\d{1,3}))?$/i.exec(String(value ?? '').trim());
679
+ if (!match || !(match[2] || match[3])) return null;
680
+ const fraction = match[3] ?? '';
681
+ let digits = BigInt(`${match[2] || '0'}${fraction}`);
682
+ let scale = fraction.length - Number(match[4] ?? 0);
683
+ if (scale < 0) {
684
+ digits *= 10n ** BigInt(-scale);
685
+ scale = 0;
686
+ }
687
+ return { digits: match[1] === '-' ? -digits : digits, scale };
688
+ }
689
+
690
+ // USD value of size × price, computed in exact decimal arithmetic from the
691
+ // strings that are signed, so the preview cannot drift from the submitted
692
+ // order through float rounding. Only the cent rounding (half up) is approximate.
693
+ function formatUsd(size, price) {
694
+ const a = parseDecimal(size);
695
+ const b = parseDecimal(price);
696
+ if (!a || !b) return null;
697
+ const product = a.digits * b.digits;
698
+ if (product < 0n) return null;
699
+ const scale = a.scale + b.scale;
700
+ let cents;
701
+ if (scale <= 2) {
702
+ cents = product * 10n ** BigInt(2 - scale);
703
+ } else {
704
+ const divisor = 10n ** BigInt(scale - 2);
705
+ cents = (product + divisor / 2n) / divisor;
706
+ }
707
+ if (product > 0n && cents === 0n) return '<$0.01';
708
+ return `~$${cents / 100n}.${String(cents % 100n).padStart(2, '0')}`;
709
+ }
710
+
711
+ // Notional of an IOC order at the reference price and at its worst fill (the
712
+ // limit price encoded after slippage), so a buy's worst-case cost is visible.
713
+ function formatIocNotional(size, referencePrice, worstPrice) {
714
+ const atReference = formatUsd(size, referencePrice);
715
+ const atWorst = formatUsd(size, worstPrice);
716
+ return atReference && atWorst ? `${atReference} at the reference price, ${atWorst} at the worst fill` : null;
717
+ }
718
+
719
+ // The order leg of a built action (not an attached take-profit/stop-loss), whose
720
+ // `s` and `p` are the exact size and limit price strings that get signed.
721
+ function mainOrderLeg(action) {
722
+ return action.orders?.find(o => !o?.t?.trigger);
723
+ }
724
+
725
+ function formatSlippage(slippage) {
726
+ return `${Number((slippage * 100).toFixed(4))}%`;
727
+ }
728
+
729
+ function builderFeeLine(status) {
730
+ const rate = builderMaxFeeRate(status.required_fee);
731
+ if (status.approved) return `${rate} of the order value (approved)`;
732
+ return `${rate} of the order value. Not yet approved: submitting signs and sends a one-time approval (max ${rate} to ${String(status.builder_address).toLowerCase()}) before the order`;
733
+ }
734
+
735
+ // An attached take-profit/stop-loss leg as it will be signed: side, size,
736
+ // reduce-only and trigger read from the built action. undefined when absent.
737
+ function describeTriggerLeg(action, tpsl, coin) {
738
+ const leg = action.orders?.find(o => o?.t?.trigger?.tpsl === tpsl);
739
+ if (!leg) return undefined;
740
+ const { isMarket, triggerPx } = leg.t.trigger;
741
+ return [
742
+ `${leg.b ? 'buy' : 'sell'} ${leg.s} ${coin}`,
743
+ ...(leg.r ? ['reduce-only'] : []),
744
+ `${isMarket ? 'market' : 'limit'} when the price reaches ${triggerPx}`,
745
+ ].join(', ');
746
+ }
747
+
748
+ // Read-only lookup of the wallet's open position in `coin`, for the plan and
749
+ // close's pre-checks. Returns the position, null when there is none, or
750
+ // undefined when the read failed or the answer for `coin` can't be trusted
751
+ // (callers then skip the checks, and the plan says so instead of guessing).
752
+ async function readOpenPosition(apiInstance, walletAddress, coin) {
753
+ try {
754
+ const result = await perpRead(apiInstance, 'positions', { wallet_address: walletAddress });
755
+ return findPosition(result?.positions, coin);
756
+ } catch {
757
+ return undefined;
758
+ }
759
+ }
760
+
761
+ // A position size as the exchange sends it: a plain decimal string, signed
762
+ // for a short. Shared by the parse and the well-formed check so they agree.
763
+ const SZI_RE = /^\s*([-+]?)(\d*\.?\d+)\s*$/;
764
+
765
+ // Side and unsigned size of a position, read from the exchange's own szi
766
+ // string, so no float conversion can round a tiny size to zero or lose its
767
+ // sign. null for a zero, missing or malformed size.
768
+ function positionSide(szi) {
769
+ const match = SZI_RE.exec(String(szi ?? ''));
770
+ if (!match || !/[1-9]/.test(match[2])) return null;
771
+ return { side: match[1] === '-' ? 'short' : 'long', size: match[2] };
772
+ }
773
+
774
+ // The coin's position, null when there is none (no entry, or a zero size), or
775
+ // undefined when the answer can't be trusted: `positions` is not a list, or
776
+ // this coin's entry has a missing or unreadable size. Entries that are not
777
+ // objects or carry no coin name can't be matched and are skipped, and a bad
778
+ // entry for another coin is ignored, so neither switches off this coin's checks.
779
+ // The first entry for the coin wins.
780
+ function findPosition(positions, coin) {
781
+ if (!Array.isArray(positions)) return undefined;
782
+ const pos = positions.find(p => p !== null && typeof p === 'object'
783
+ && p.coin != null && String(p.coin).toUpperCase() === coin);
784
+ if (!pos) return null;
785
+ if (positionSide(pos.szi)) return pos;
786
+ return SZI_RE.test(String(pos.szi ?? '')) ? null : undefined;
787
+ }
788
+
789
+ function describePosition(pos) {
790
+ if (pos === undefined) return 'could not be loaded';
791
+ if (pos === null) return 'none';
792
+ const { side, size } = positionSide(pos.szi);
793
+ const lev = formatPositionLeverage(pos.leverage);
794
+ return `${side} ${size}${pos.entryPx ? ` @ ${pos.entryPx}` : ''}${lev ? `, ${lev}` : ''}`;
795
+ }
796
+
797
+ // Leverage that applies to an order in `coin`: Hyperliquid uses the wallet's
798
+ // per-asset setting, which an open position reports.
799
+ function describeOrderLeverage(pos, coin) {
800
+ const lev = pos ? formatPositionLeverage(pos.leverage) : null;
801
+ if (lev) return `${lev} (current ${coin} setting, unchanged by this order)`;
802
+ return `your current ${coin} setting, unchanged by this order (change it with: nansen perp leverage)`;
803
+ }
804
+
805
+ // When to load the signing key. Unprompted (off a terminal, or --yes): before
806
+ // the gate, exactly where it always was, so a missing or wrong password is
807
+ // still reported before a metadata outage. Prompted: only after the user says
808
+ // yes, so a declined action never decrypts the wallet. Dry run: never for a
809
+ // local key (no password needed); a Privy wallet still has its id/address
810
+ // binding checked, which loads no key, so the preview fails the way the real
811
+ // run would. Returns null when the caller resolves the context after the gate.
812
+ async function signingCtxBeforeGate(wallet, guard, log) {
813
+ if (guard.dryRun) return wallet.provider === 'privy' ? resolveSigningCtx(wallet, log) : null;
814
+ if (guard.isTTY && !guard.assumeYes) return null;
815
+ return resolveSigningCtx(wallet, log);
816
+ }
817
+
818
+ // Print the plan and ask for confirmation when needed. Returns false when a
819
+ // dry run has finished, true to go on and sign. The plan (and the reads it
820
+ // makes) is only built when it will be shown, so the unprompted path makes no
821
+ // extra requests.
822
+ async function guardPerpAction(apiInstance, { guard, walletAddress, buildPlan, question }, deps) {
823
+ const showPlan = guard.dryRun || (guard.isTTY && !guard.assumeYes);
824
+ // On a dry run, screen as a real run would right before signing, so a
825
+ // preview of a blocked wallet fails the same way instead of looking clean.
826
+ // The plan's reads fail open, so only the screen can throw here.
827
+ const [plan] = await Promise.all([
828
+ showPlan ? buildPlan() : '',
829
+ guard.dryRun ? screenOrThrow(apiInstance, [walletAddress]) : undefined,
830
+ ]);
831
+ return guardExecution({
832
+ plan,
833
+ ...guard,
834
+ promptFn: deps.promptFn,
835
+ log: deps.log,
836
+ confirmationLog: deps.confirmationLog,
837
+ question,
838
+ dryRunNotice: PERP_DRY_RUN_NOTICE,
839
+ });
840
+ }
841
+
660
842
  // ── Command builder ──────────────────────────────────────────────────
661
843
 
844
+ // Hyperliquid reports each position's leverage setting as { type, value }
845
+ // (type is "cross" or "isolated"). The liquidation price is the exchange's own
846
+ // figure and only makes sense next to it: on cross margin it depends on the
847
+ // whole account's equity, so even a 1x position can have a liquidation price
848
+ // near the current price. Returns e.g. "1x cross", or null when absent.
849
+ export function formatPositionLeverage(leverage) {
850
+ if (!leverage || typeof leverage !== 'object') return null;
851
+ const value = Number(leverage.value);
852
+ const hasValue = leverage.value !== null && leverage.value !== '' && Number.isFinite(value);
853
+ const type = typeof leverage.type === 'string' && leverage.type ? leverage.type : null;
854
+ if (!hasValue && !type) return null;
855
+ return [hasValue ? `${value}x` : null, type].filter(Boolean).join(' ');
856
+ }
857
+
662
858
  export function buildPerpCommands(deps = {}) {
663
859
  const {
664
860
  log = console.log,
665
861
  warn = (m) => process.stderr.write(`${m}\n`),
666
862
  track = trackPerpOrderCompleted,
863
+ // Confirmation seams, wired by the CLI exactly as for trade/bridge execute.
864
+ // A library caller that passes none is non-interactive (isTTY false).
865
+ promptFn,
866
+ confirmationLog = log,
867
+ isTTY = false,
868
+ env = process.env,
667
869
  } = deps;
870
+ const guardDeps = { promptFn, log, confirmationLog };
668
871
 
669
872
  return {
670
873
  'order': async (args, apiInstance, flags, options) => {
@@ -685,7 +888,9 @@ OPTIONS:
685
888
  --slippage Slippage for market orders (default 0.03 = 3%)
686
889
  --take-profit Take-profit trigger price
687
890
  --stop-loss Stop-loss trigger price
688
- --wallet Wallet name`, 'MISSING_PARAM');
891
+ --wallet Wallet name
892
+ --dry-run Validate and print the order plan; sign and send nothing
893
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1)`, 'MISSING_PARAM');
689
894
  }
690
895
 
691
896
  const side = assertSide(options.side, ORDER_SIDES);
@@ -697,6 +902,7 @@ OPTIONS:
697
902
  const tp = options['take-profit'] !== undefined ? parsePositiveNumber(options['take-profit'], 'take-profit') : undefined;
698
903
  const sl = options['stop-loss'] !== undefined ? parsePositiveNumber(options['stop-loss'], 'stop-loss') : undefined;
699
904
  const isBuy = side === 'buy' || side === 'long';
905
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
700
906
 
701
907
  // buildOrderAction re-checks this, but that call happens after the signing
702
908
  // context is resolved and after ensureBuilderApproved has already signed
@@ -713,20 +919,19 @@ OPTIONS:
713
919
  warnImpreciseValue(coin, assetMeta?.szDecimals, { sizeRaw: options.size, priceRaw: options.price }, warn);
714
920
 
715
921
  const wallet = resolveWalletAddress(walletName);
716
- const ctx = await resolveSigningCtx(wallet, log);
922
+ let ctx = await signingCtxBeforeGate(wallet, guard, log);
717
923
 
718
924
  const { assetId, szDecimals } = requireAsset(assetMeta, coin);
719
925
 
720
- log(`\n Perp Order: ${coin} ${isBuy ? 'LONG' : 'SHORT'} ${size} @ ${price} (${orderType})`);
721
-
722
926
  // Single source of truth for the builder code + approval gate (D1).
723
927
  // On the first trade this screens the wallet once for the builder-fee
724
928
  // approval and again for the order itself. The two round-trips are
725
929
  // deliberate: each signed action re-screens the signer, so this is not
726
930
  // duplication to collapse.
727
931
  const builderStatus = await fetchBuilderFee(apiInstance, wallet.address);
728
- await ensureBuilderApproved(apiInstance, builderStatus, ctx);
729
932
 
933
+ // Built (pure, nothing signed) before the gate so the plan shows the
934
+ // rounded size and price that will actually be encoded.
730
935
  const { action, size: effSize, price: effPrice } = buildOrderAction(
731
936
  {
732
937
  isBuy,
@@ -742,6 +947,41 @@ OPTIONS:
742
947
  },
743
948
  { assetId, szDecimals },
744
949
  );
950
+
951
+ // Before the builder-fee approval: a dry run or a declined prompt must not
952
+ // put that one-time approval on-chain either.
953
+ const proceed = await guardPerpAction(apiInstance, {
954
+ guard,
955
+ walletAddress: wallet.address,
956
+ question: 'Submit this order to Hyperliquid? [y/N] ',
957
+ buildPlan: async () => {
958
+ const position = await readOpenPosition(apiInstance, wallet.address, coin);
959
+ return formatPlan(`Perp order plan — ${coin}`, [
960
+ ['Wallet', wallet.address],
961
+ ['Side', `${isBuy ? 'buy' : 'sell'} (${isBuy ? 'long' : 'short'})`],
962
+ ['Size', `${effSize} ${coin}`],
963
+ ['Type', orderType === 'market' ? 'market (IOC)' : `limit (${tif})`],
964
+ ['Price', orderType === 'market'
965
+ ? `${price} reference, worst fill ${effPrice} (${formatSlippage(slippage)} slippage)`
966
+ : String(effPrice)],
967
+ ['Take-profit', describeTriggerLeg(action, 'tp', coin)],
968
+ ['Stop-loss', describeTriggerLeg(action, 'sl', coin)],
969
+ ['Est. notional', orderType === 'market'
970
+ ? formatIocNotional(mainOrderLeg(action)?.s, String(price), mainOrderLeg(action)?.p)
971
+ : formatUsd(mainOrderLeg(action)?.s, mainOrderLeg(action)?.p)],
972
+ ['Leverage', describeOrderLeverage(position, coin)],
973
+ ['Open position', describePosition(position)],
974
+ ['Builder fee', builderFeeLine(builderStatus)],
975
+ ]);
976
+ },
977
+ }, guardDeps);
978
+ if (!proceed) return undefined;
979
+ ctx ??= await resolveSigningCtx(wallet, log);
980
+
981
+ log(`\n Perp Order: ${coin} ${isBuy ? 'LONG' : 'SHORT'} ${size} @ ${price} (${orderType})`);
982
+
983
+ await ensureBuilderApproved(apiInstance, builderStatus, ctx);
984
+
745
985
  const nonce = hlNonce();
746
986
  const eip712 = l1Eip712(action, null, nonce);
747
987
 
@@ -771,19 +1011,48 @@ OPTIONS:
771
1011
  const walletName = scalar(options.wallet, 'wallet');
772
1012
 
773
1013
  if (!coin || options.oid === undefined) {
774
- throw new CommandError('Usage: nansen perp cancel --coin <symbol> --oid <orderId> [--wallet <name>]', 'MISSING_PARAM');
1014
+ throw new CommandError('Usage: nansen perp cancel --coin <symbol> --oid <orderId> [--wallet <name>] [--dry-run] [--yes]', 'MISSING_PARAM');
775
1015
  }
776
1016
 
777
1017
  const oid = parsePositiveInt(options.oid, 'oid');
1018
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
778
1019
 
779
1020
  const assetMeta = await fetchAssetMeta(apiInstance, coin);
780
1021
  const wallet = resolveWalletAddress(walletName);
781
- const ctx = await resolveSigningCtx(wallet, log);
1022
+ let ctx = await signingCtxBeforeGate(wallet, guard, log);
782
1023
  const { assetId } = requireAsset(assetMeta, coin);
783
1024
 
1025
+ const { action } = buildCancelAction({ orderId: oid }, { assetId });
1026
+
1027
+ const proceed = await guardPerpAction(apiInstance, {
1028
+ guard,
1029
+ walletAddress: wallet.address,
1030
+ question: 'Submit this cancel to Hyperliquid? [y/N] ',
1031
+ buildPlan: async () => {
1032
+ let order;
1033
+ try {
1034
+ const result = await perpRead(apiInstance, 'orders', { wallet_address: wallet.address });
1035
+ const match = (result.orders || []).find(o => Number(o.oid) === oid && String(o.coin).toUpperCase() === coin);
1036
+ // Hyperliquid reports a resting order's side as B (bid) or A (ask).
1037
+ const orderSide = { B: 'buy', A: 'sell' }[match?.side] ?? match?.side;
1038
+ order = match
1039
+ ? `${orderSide} ${match.sz} @ ${match.limitPx}`
1040
+ : `not among the open ${coin} orders (Hyperliquid rejects the cancel if the order is not open)`;
1041
+ } catch {
1042
+ order = 'could not load open orders';
1043
+ }
1044
+ return formatPlan(`Perp cancel plan — ${coin}`, [
1045
+ ['Wallet', wallet.address],
1046
+ ['Order id', String(oid)],
1047
+ ['Order', order],
1048
+ ]);
1049
+ },
1050
+ }, guardDeps);
1051
+ if (!proceed) return undefined;
1052
+ ctx ??= await resolveSigningCtx(wallet, log);
1053
+
784
1054
  log(`\n Cancel: ${coin} order #${oid}`);
785
1055
 
786
- const { action } = buildCancelAction({ orderId: oid }, { assetId });
787
1056
  const nonce = hlNonce();
788
1057
  const eip712 = l1Eip712(action, null, nonce);
789
1058
 
@@ -801,7 +1070,9 @@ OPTIONS:
801
1070
  `Usage: nansen perp close --coin <symbol> --size <amount> --price <markPrice> --side <buy|sell> [options]
802
1071
 
803
1072
  --side buy (closing a short) or sell (closing a long)
804
- --slippage Slippage tolerance (default 0.03 = 3%)`, 'MISSING_PARAM');
1073
+ --slippage Slippage tolerance (default 0.03 = 3%)
1074
+ --dry-run Validate and print the close plan; sign and send nothing
1075
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1)`, 'MISSING_PARAM');
805
1076
  }
806
1077
 
807
1078
  const side = assertSide(options.side, CLOSE_SIDES);
@@ -809,6 +1080,7 @@ OPTIONS:
809
1080
  const price = parsePositiveNumber(options.price, 'price');
810
1081
  const slippage = options.slippage !== undefined ? parseSlippage(options.slippage) : 0.03;
811
1082
  const isBuy = side === 'buy';
1083
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
812
1084
 
813
1085
  // Advisory: warn before signing if the close size is finer than the asset
814
1086
  // allows (Hyperliquid rounds rather than rejects). --price here is only a
@@ -822,39 +1094,69 @@ OPTIONS:
822
1094
  // fails fast with a clear message instead of the backend's opaque "reduce
823
1095
  // only order would increase position". sell closes a long, buy closes a
824
1096
  // short. Fall open if positions can't be fetched — HL still checks.
825
- let openPositions = null;
826
- try {
827
- const result = await perpRead(apiInstance, 'positions', { wallet_address: wallet.address });
828
- openPositions = result.positions || [];
829
- } catch {
830
- // positions lookup failed — skip the direction pre-check.
1097
+ // undefined: lookup failed or malformed (skip the checks); null: no position.
1098
+ const openPosition = await readOpenPosition(apiInstance, wallet.address, coin);
1099
+ // The lookup worked and there is nothing to close: a reduce-only order
1100
+ // would be rejected by Hyperliquid, so a dry run must not report success.
1101
+ // Only the dry run fails here. A real close still goes to Hyperliquid,
1102
+ // which holds the live state: the proxy's positions can lag a fill that
1103
+ // just happened, and a stale "none" must never block a risk-reducing close.
1104
+ if (openPosition === null && guard.dryRun) {
1105
+ // An unknown coin or a metadata outage is the more useful answer, and a
1106
+ // dry run screens the wallet as guardPerpAction would (a blocked wallet
1107
+ // must fail the preview the same way whether or not it has a position).
1108
+ requireAsset(assetMeta, coin);
1109
+ await screenOrThrow(apiInstance, [wallet.address]);
1110
+ throw new CommandError(
1111
+ `No open ${coin} position to close for ${wallet.address}. Check with: nansen perp positions. If you opened it moments ago, the positions data may not show it yet; retry in a few seconds.`,
1112
+ 'NO_OPEN_POSITION',
1113
+ );
831
1114
  }
832
- if (openPositions) {
833
- const pos = openPositions.find(p => String(p.coin).toUpperCase() === coin);
834
- const szi = pos ? parseFloat(pos.szi) : NaN;
835
- if (Number.isFinite(szi) && szi !== 0) {
836
- const requiredSide = szi > 0 ? 'sell' : 'buy';
837
- if (side !== requiredSide) {
838
- const posSide = szi > 0 ? 'long' : 'short';
839
- throw invalid(
840
- `Cannot close a ${posSide} ${coin} position with --side ${side}. Use --side ${requiredSide} (sell closes a long, buy closes a short).`,
841
- );
842
- }
1115
+ if (openPosition) {
1116
+ const posSide = positionSide(openPosition.szi).side;
1117
+ const requiredSide = posSide === 'long' ? 'sell' : 'buy';
1118
+ if (side !== requiredSide) {
1119
+ throw invalid(
1120
+ `Cannot close a ${posSide} ${coin} position with --side ${side}. Use --side ${requiredSide} (sell closes a long, buy closes a short).`,
1121
+ );
843
1122
  }
844
1123
  }
845
1124
 
846
- const ctx = await resolveSigningCtx(wallet, log);
1125
+ let ctx = await signingCtxBeforeGate(wallet, guard, log);
847
1126
  const { assetId, szDecimals } = requireAsset(assetMeta, coin);
848
1127
 
849
- log(`\n Close: ${coin} ${isBuy ? 'buy-to-close' : 'sell-to-close'} ${size} @ ${price}`);
850
-
851
1128
  const builderStatus = await fetchBuilderFee(apiInstance, wallet.address);
852
- await ensureBuilderApproved(apiInstance, builderStatus, ctx);
853
1129
 
854
1130
  const { action, size: effSize, price: effPrice } = buildCloseAction(
855
1131
  { size, price, isBuy, slippage, builder: builderCode(builderStatus) },
856
1132
  { assetId, szDecimals },
857
1133
  );
1134
+
1135
+ const proceed = await guardPerpAction(apiInstance, {
1136
+ guard,
1137
+ walletAddress: wallet.address,
1138
+ question: 'Submit this close order to Hyperliquid? [y/N] ',
1139
+ buildPlan: async () => formatPlan(`Perp close plan — ${coin}`, [
1140
+ ['Wallet', wallet.address],
1141
+ ['Side', `${side} (${isBuy ? 'closes a short' : 'closes a long'}, reduce-only)`],
1142
+ ['Size', `${effSize} ${coin}`],
1143
+ ['Type', 'market (IOC)'],
1144
+ ['Price', `${price} reference, worst fill ${effPrice} (${formatSlippage(slippage)} slippage)`],
1145
+ ...(openPosition === null
1146
+ ? [['Warning', `no open ${coin} position in the positions data; Hyperliquid rejects a reduce-only close with nothing to close (the data can lag a fill that just happened)`]]
1147
+ : []),
1148
+ ['Est. notional', formatIocNotional(mainOrderLeg(action)?.s, String(price), mainOrderLeg(action)?.p)],
1149
+ ['Open position', describePosition(openPosition)],
1150
+ ['Builder fee', builderFeeLine(builderStatus)],
1151
+ ]),
1152
+ }, guardDeps);
1153
+ if (!proceed) return undefined;
1154
+ ctx ??= await resolveSigningCtx(wallet, log);
1155
+
1156
+ log(`\n Close: ${coin} ${isBuy ? 'buy-to-close' : 'sell-to-close'} ${size} @ ${price}`);
1157
+
1158
+ await ensureBuilderApproved(apiInstance, builderStatus, ctx);
1159
+
858
1160
  const nonce = hlNonce();
859
1161
  const eip712 = l1Eip712(action, null, nonce);
860
1162
 
@@ -884,11 +1186,12 @@ OPTIONS:
884
1186
  const walletName = scalar(options.wallet, 'wallet');
885
1187
 
886
1188
  if (!coin || options.leverage === undefined) {
887
- throw new CommandError('Usage: nansen perp leverage --coin <symbol> --leverage <n> [--margin-type cross|isolated] [--wallet <name>]', 'MISSING_PARAM');
1189
+ throw new CommandError('Usage: nansen perp leverage --coin <symbol> --leverage <n> [--margin-type cross|isolated] [--wallet <name>] [--dry-run] [--yes]', 'MISSING_PARAM');
888
1190
  }
889
1191
 
890
1192
  const marginType = assertMarginType(options['margin-type']);
891
1193
  const leverage = parsePositiveInt(options.leverage, 'leverage');
1194
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
892
1195
 
893
1196
  // Pre-validate against the asset's max leverage so an over-max value fails
894
1197
  // fast with a clear message instead of an opaque HL rejection. Falls open
@@ -901,12 +1204,31 @@ OPTIONS:
901
1204
 
902
1205
  const isCross = marginType === 'cross';
903
1206
  const wallet = resolveWalletAddress(walletName);
904
- const ctx = await resolveSigningCtx(wallet, log);
1207
+ let ctx = await signingCtxBeforeGate(wallet, guard, log);
905
1208
  const { assetId } = requireAsset(assetMeta, coin);
906
1209
 
1210
+ const { action } = buildLeverageAction({ leverage, isCross }, { assetId });
1211
+
1212
+ const proceed = await guardPerpAction(apiInstance, {
1213
+ guard,
1214
+ walletAddress: wallet.address,
1215
+ question: 'Submit this leverage change to Hyperliquid? [y/N] ',
1216
+ buildPlan: async () => {
1217
+ const position = await readOpenPosition(apiInstance, wallet.address, coin);
1218
+ return formatPlan(`Perp leverage plan — ${coin}`, [
1219
+ ['Wallet', wallet.address],
1220
+ ['Leverage', `${leverage}x`],
1221
+ ['Margin type', marginType],
1222
+ ['Asset maximum', Number.isFinite(assetMeta.maxLeverage) ? `${assetMeta.maxLeverage}x` : null],
1223
+ ['Open position', describePosition(position)],
1224
+ ]);
1225
+ },
1226
+ }, guardDeps);
1227
+ if (!proceed) return undefined;
1228
+ ctx ??= await resolveSigningCtx(wallet, log);
1229
+
907
1230
  log(`\n Leverage: ${coin} ${leverage}x ${isCross ? 'cross' : 'isolated'}`);
908
1231
 
909
- const { action } = buildLeverageAction({ leverage, isCross }, { assetId });
910
1232
  const nonce = hlNonce();
911
1233
  const eip712 = l1Eip712(action, null, nonce);
912
1234
 
@@ -984,7 +1306,8 @@ OPTIONS:
984
1306
  log(`\n Open Positions (${positions.length}):`);
985
1307
  for (const p of positions) {
986
1308
  const side = parseFloat(p.szi) >= 0 ? 'LONG' : 'SHORT';
987
- log(` ${p.coin} ${side} size=${p.szi} entry=${p.entryPx} pnl=${p.unrealizedPnl} liq=${p.liquidationPx || 'n/a'}`);
1309
+ const lev = formatPositionLeverage(p.leverage);
1310
+ log(` ${p.coin} ${side} size=${p.szi} entry=${p.entryPx} pnl=${p.unrealizedPnl}${lev ? ` lev=${lev}` : ''} liq=${p.liquidationPx || 'n/a'}`);
988
1311
  }
989
1312
  log('');
990
1313
  return undefined;
package/src/privy.js CHANGED
@@ -11,7 +11,7 @@ import path from "path";
11
11
  import { parsePaymentRequirements } from "./x402.js";
12
12
  import { hasSufficientEvmPaymentBalance, hasSufficientSvmPaymentBalance } from "./x402-payment-balance.js";
13
13
  import { isEvmNetwork } from "./x402-evm.js";
14
- import { mkdirPrivateSync, readWalletJson, writeWalletJsonAtomic } from "./wallet.js";
14
+ import { mkdirPrivateSync, readWalletJson, validateWalletName, withWalletLock, writeWalletJsonAtomic } from "./wallet.js";
15
15
  import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo, signWithSessionCharge } from "./x402-policy.js";
16
16
  import {
17
17
  isSvmNetwork,
@@ -152,6 +152,54 @@ export class PrivyClient {
152
152
 
153
153
  // ============= Helpers =============
154
154
 
155
+ function extractPrivyWalletAddress(response) {
156
+ return response?.address
157
+ ?? response?.data?.address
158
+ ?? response?.wallet?.address
159
+ ?? response?.data?.wallet?.address
160
+ ?? null;
161
+ }
162
+
163
+ /**
164
+ * Resolve a Privy wallet ID and bind it to the address stored locally before
165
+ * any preview, screening, or signing can rely on that address.
166
+ */
167
+ export async function assertPrivyWalletAddress(client, walletId, expectedAddress, chainType) {
168
+ if (chainType !== 'evm' && chainType !== 'solana') {
169
+ throw new Error(`Unsupported Privy wallet chain type: ${chainType}`);
170
+ }
171
+ const label = chainType === 'solana' ? 'Solana' : 'EVM';
172
+ if (!walletId) {
173
+ throw new Error(`No Privy ${label} wallet ID found. Re-create the wallet with: nansen wallet create --provider privy`);
174
+ }
175
+ if (!expectedAddress) {
176
+ throw new Error(`No ${label} address is stored for this Privy wallet. Re-create the wallet with: nansen wallet create --provider privy`);
177
+ }
178
+
179
+ const response = await client.getWallet(walletId);
180
+ const authoritativeAddress = extractPrivyWalletAddress(response);
181
+ const validAddress = chainType === 'evm'
182
+ ? /^0x[0-9a-f]{40}$/i
183
+ : /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
184
+ if (typeof authoritativeAddress !== 'string' || !validAddress.test(authoritativeAddress)) {
185
+ throw new Error(`Privy returned no valid ${label} address for the selected wallet ID. Re-create the wallet with: nansen wallet create --provider privy`);
186
+ }
187
+ if (typeof expectedAddress !== 'string' || !validAddress.test(expectedAddress)) {
188
+ throw new Error(`The locally stored Privy ${label} address is invalid. Re-create the wallet with: nansen wallet create --provider privy`);
189
+ }
190
+
191
+ const matches = chainType === 'evm'
192
+ ? authoritativeAddress.toLowerCase() === String(expectedAddress).toLowerCase()
193
+ : authoritativeAddress === expectedAddress;
194
+ if (!matches) {
195
+ throw new Error(
196
+ `The selected Privy wallet ID does not match the locally stored ${label} address. Re-create the wallet with: nansen wallet create --provider privy`,
197
+ );
198
+ }
199
+
200
+ return authoritativeAddress;
201
+ }
202
+
155
203
  function getClient() {
156
204
  return new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
157
205
  }
@@ -161,10 +209,7 @@ function getClient() {
161
209
  * Mirrors createWallet() in wallet.js but for Privy server wallets.
162
210
  */
163
211
  export async function createPrivyWalletPair(name) {
164
- const WALLET_NAME_RE = /^[a-zA-Z0-9_-]{1,64}$/;
165
- if (!name || !WALLET_NAME_RE.test(name)) {
166
- throw new Error("Wallet name must be 1-64 characters: letters, numbers, hyphens, underscores only");
167
- }
212
+ validateWalletName(name, { creating: true });
168
213
 
169
214
  const walletsDir = path.join(process.env.HOME || process.env.USERPROFILE || "", ".nansen", "wallets");
170
215
  const walletFile = path.join(walletsDir, `${name}.json`);
@@ -195,18 +240,48 @@ export async function createPrivyWalletPair(name) {
195
240
 
196
241
  mkdirPrivateSync(walletsDir);
197
242
 
198
- // Write config before wallet file so a crash doesn't leave an orphan without a default entry
199
- const configPath = path.join(walletsDir, "config.json");
200
- let config = { defaultWallet: null, passwordHash: null };
201
- if (fs.existsSync(configPath)) {
202
- config = readWalletJson(configPath);
203
- }
204
- if (!config.defaultWallet) {
205
- config.defaultWallet = name;
206
- writeWalletJsonAtomic(configPath, config);
243
+ // Only the local save is locked; the Privy calls above stay outside it. So
244
+ // re-check the name here: another command may have taken it meanwhile.
245
+ const deleteRemote = async () => {
246
+ try { await client.deleteWallet(evmResult.id); } catch { /* best effort */ }
247
+ try { await client.deleteWallet(solanaResult.id); } catch { /* best effort */ }
248
+ };
249
+ let saved;
250
+ try {
251
+ saved = withWalletLock(() => {
252
+ if (fs.existsSync(walletFile)) return false;
253
+
254
+ const configPath = path.join(walletsDir, "config.json");
255
+ let config = { defaultWallet: null, passwordHash: null };
256
+ if (fs.existsSync(configPath)) {
257
+ config = readWalletJson(configPath);
258
+ }
259
+
260
+ // Wallet file first, as createWallet does: if the config write then
261
+ // fails, the file is removed, so config never names a missing wallet.
262
+ writeWalletJsonAtomic(walletFile, walletData);
263
+ if (!config.defaultWallet) {
264
+ config.defaultWallet = name;
265
+ try {
266
+ writeWalletJsonAtomic(configPath, config);
267
+ } catch (err) {
268
+ fs.rmSync(walletFile, { force: true });
269
+ throw err;
270
+ }
271
+ }
272
+ return true;
273
+ });
274
+ } catch (err) {
275
+ // Busy lock or unreadable config: nothing local references the new
276
+ // Privy wallets, so remove them rather than orphan them.
277
+ await deleteRemote();
278
+ throw err;
207
279
  }
208
280
 
209
- writeWalletJsonAtomic(walletFile, walletData);
281
+ if (!saved) {
282
+ await deleteRemote();
283
+ throw new Error(`Wallet "${name}" already exists`);
284
+ }
210
285
 
211
286
  return walletData;
212
287
  }